code stringlengths 2 1.05M |
|---|
/**
* The overview of the chart's series
*/
var Legend = Highcharts.Legend = function (chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function (chart, options) {
var legend = this,
itemStyle = options.itemStyle,
padding,
itemMarginTop = options.itemMarginTop || 0;
this.options = options;
if (!options.enabled) {
return;
}
legend.itemStyle = itemStyle;
legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
legend.itemMarginTop = itemMarginTop;
legend.padding = padding = pick(options.padding, 8);
legend.initialItemX = padding;
legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
legend.maxItemWidth = 0;
legend.chart = chart;
legend.itemHeight = 0;
legend.symbolWidth = pick(options.symbolWidth, 16);
legend.pages = [];
// Render it
legend.render();
// move checkboxes
addEvent(legend.chart, 'endResize', function () {
legend.positionCheckboxes();
});
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function (item, visible) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = { fill: symbolColor },
key,
val;
if (legendItem) {
legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
symbolAttr.stroke = symbolColor;
markerOptions = item.convertAttribs(markerOptions);
for (key in markerOptions) {
val = markerOptions[key];
if (val !== UNDEFINED) {
symbolAttr[key] = val;
}
}
}
legendSymbol.attr(symbolAttr);
}
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox,
legendGroup = item.legendGroup;
if (legendGroup && legendGroup.element) {
legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function () {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({ zIndex: 1 })
.css(titleOptions.style)
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Set the legend item text
*/
setText: function (item) {
var options = this.options;
item.legendItem.attr({
text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item)
});
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
series = item.series && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
'',
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li);
legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// Always update the text
legend.setText(item);
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line (#915, #3976)
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || mathMax(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function (margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align[0] + options.verticalAlign[0] + options.layout[0];
if (this.display && !options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function (alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = mathMax(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
[1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
legendBorderWidth = options.borderWidth,
legendBackgroundColor = options.backgroundColor;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function (item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (legendBorderWidth || legendBackgroundColor) {
if (!box) {
legend.box = box = renderer.rect(
0,
0,
legendWidth,
legendHeight,
options.borderRadius,
legendBorderWidth || 0
).attr({
stroke: options.borderColor,
'stroke-width': legendBorderWidth || 0,
fill: legendBackgroundColor || NONE
})
.add(legendGroup)
.shadow(options.shadow);
box.isNew = true;
} else if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({ width: legendWidth, height: legendHeight })
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function (item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
padding = this.padding,
lastY,
allItems = this.allItems,
clipToHeight = function (height) {
clipRect.attr({
height: height
});
// useHTML
if (legend.contentGroup.div) {
legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
}
};
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = mathMin(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight) {
this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function (item, i) {
var y = item._legendItemPos[1],
h = mathRound(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipToHeight(clipHeight);
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.css(navOptions.style)
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipToHeight(chart.chartHeight);
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function (legend, item) {
var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f;
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - symbolHeight + 1, // #3988
legend.symbolWidth,
symbolHeight,
legend.options.symbolRadius || 0
).attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// TODO: Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
|
import Ember from 'ember';
const {
Component,
} = Ember;
/**
`progress-bar-container` is the container for a progress-bar.
## default usage
```Handlebars
{{progress-bar-container percentage=percentage}}
```
@class progress-bar-container
@module Component
@extends Ember.Component
*/
export default Component.extend({
classNames: ['progress-bar-container'],
});
|
SC.stringsFor("tr", {
"DG.fileMenu.menuItem.newDocument": "Yeni",
"DG.fileMenu.menuItem.openDocument": "Aç...",
"DG.fileMenu.menuItem.closeDocument": "Kapat",
"DG.fileMenu.menuItem.importFile": "İçe aktar",
"DG.fileMenu.menuItem.revertTo": "Dönüştür...",
"DG.fileMenu.menuItem.revertToOpened": "Son açılan versiyon",
"DG.fileMenu.menuItem.revertToShared": "Paylaşılan görünümler",
"DG.fileMenu.menuItem.saveDocument": "Kaydet...",
"DG.fileMenu.menuItem.copyDocument": "Kopya Oluştur",
"DG.fileMenu.menuItem.share": "Paylaş",
"DG.fileMenu.menuItem.shareGetLink": "Paylaşılan görünümler bağlantısı",
"DG.fileMenu.menuItem.shareUpdate": "Paylaşılan görünümleri güncelle",
"DG.fileMenu.menuItem.renameDocument": "Yeniden adlandır",
"DG.main.userEntryView.title": "Ne yapmak istiyorsun?",
"DG.main.userEntryView.openDocument": "Dosya Aç veya Örnekleri Görüntüle",
"DG.main.userEntryView.newDocument": "Yeni Dosya Aç",
"DG.mainPage.mainPane.undoButton.title": "Geri Al",
"DG.mainPage.mainPane.undoButton.toolTip": "Son yapılanı geri al",
"DG.mainPage.mainPane.redoButton.title": "Yinele",
"DG.mainPage.mainPane.redoButton.toolTip": "Son geri alınanı yinele",
"DG.mainPage.mainPane.versionString": "Versiyon %@ (%@)",
"DG.mainPage.mainPane.messageView.value": "Üzgünüz, CODAP tarayıcınız tarafından desteklenmiyor. CODAP sadece Firefox 46+, Chrome 50+, Windows Edge 14+, ve Safari 10+ tarafından desteklenmektedir. Şu anda diğer tarayıcılar tarafından desteklenmemektedir.",
"DG.mainPage.titleBar.saved": "Dosya Kaydedildi!",
"DG.mainPage.mainPane.versionString.IS_BUILD": "Versiyon %@ (%@ IS)",
"DG.mainPage.mainPane.versionString.SRRI_BUILD": "Versiyon %@ (%@.srri10)",
"DG.AppController.resetData.title": "Verileri temizle...",
"DG.AppController.resetData.toolTip": "Bu dosyadaki tüm verileri sil",
"DG.AppController.resetData.warnMessage": "Bu dosyadaki tüm verileri gerçekten silmek istiyor musunuz?",
"DG.AppController.resetData.warnDescription": "Bu işlem geri alınamaz.",
"DG.AppController.resetData.okButtonTitle": "Evet, tüm verileri sil",
"DG.AppController.resetData.cancelButtonTitle": "Hayır, verileri sakla",
"DG.AppController.closeDocument.warnMessage": "Dosyayı kaydetmeden kapatmak istiyor musunuz?",
"DG.AppController.closeDocument.warnDescription": "Bu işlem geri alınamaz.",
"DG.AppController.closeDocument.okButtonTitle": "Kapat",
"DG.AppController.closeDocument.cancelButtonTitle": "İptal et",
"DG.AppController.beforeUnload.confirmationMessage": "Bu dosyada kaydedilmeyen değişiklikler var.",
"DG.AppController.optionMenuItems.reportProblem": "Yorum Gönder...",
"DG.AppController.optionMenuItems.viewWebPage": "İnternet sayfasını görüntüle...",
"DG.AppController.optionMenuItems.configureGuide": "Rehberi Yapılandır...\n",
"DG.AppController.optionMenuItems.about": "CODAP Hakkında...",
"DG.AppController.optionMenuItems.releaseNotes": "Yenilikler",
"DG.AppController.optionMenuItems.help": "Yardım...",
"DG.AppController.optionMenuItems.toWebSite": "CODAP internet sayfası",
"DG.AppController.exportDocument.prompt": "Dosya adı:",
"DG.AppController.exportCaseData.prompt": "Verileri buradan dışarı aktar:",
"DG.AppController.exportDocument.exportTitle": "Dışa aktar",
"DG.AppController.exportDocument.exportTooltip": "Verileri bir dosyaya aktar",
"DG.AppController.exportDocument.cancelTitle": "İptal et",
"DG.AppController.exportDocument.cancelTooltip": "Dışa aktarımı iptal et",
"DG.AppController.feedbackDialog.dialogTitle": "Yorum Yap",
"DG.AppController.feedbackDialog.subHeaderText": "Yorumlarınız bizim için önemli!",
"DG.AppController.feedbackDialog.messageText": "Ürünümüzü geliştirmemize yardımcı olun. Sorularınızı, isteklerinizi ve sistem hatalarını bize bildirin. Teşekkür ederiz!",
"DG.AppController.feedbackDialog.subjectHint": "Yorumunuz ne hakkında",
"DG.AppController.feedbackDialog.feedbackHint": "Ayrıntılar",
"DG.AppController.feedbackDialog.submitFeedbackButton": "Gönder",
"DG.AppController.feedbackDialog.cancelFeedbackButton": "İptal et",
"DG.AppController.showWebSiteTitle": "CODAP Hakkında",
"DG.AppController.showHelpTitle": "CODAP için Destek",
"DG.AppController.showAboutTitle": "CODAP Hakkında",
"DG.AppController.showReleaseNotesTitle": "CODAP Sürüm Notları",
"DG.AppController.dropFile.error": "Hata: %@1",
"DG.AppController.dropFile.unknownFileType": "Bu dosya türünü aktaramazsınız",
"DG.AppController.validateDocument.missingRequiredProperty": "Gerekli özellik bulunamadı: %@1",
"DG.AppController.validateDocument.unexpectedProperty": "Beklenmeyen üst düzey özellik: %@1",
"DG.AppController.validateDocument.unresolvedID": "Çözümlenmemiş kimlik: %@1",
"DG.AppController.validateDocument.parseError": "Belgede ayrıştırma hatası: %@1\n",
"DG.AppController.validateDocument.invalidDocument": "Geçersiz JSON Dosyası: %@1",
"DG.AppController.openDocument.error.general": "Dosya açılamadı",
"DG.AppController.openDocument.error.invalid_format": "CODAP bu tür dosyaları çalıştıramıyor",
"DG.AppController.createDataSet.initialAttribute": "Özellik",
"DG.AppController.createDataSet.name": "Yeni Veri Seti",
"DG.AppController.createDataSet.collectionName": "Durumlar",
"DG.AppController.caseTableMenu.newDataSet": "-- yeni --",
"DG.SingleTextDialog.okButton.title": "TAMAM",
"DG.SingleTextDialog.cancelButton.title": "İptal et",
"DG.SingleTextDialog.cancelButton.toolTip": "Herhangi bir değişiklik yapmadan iletişim kutusunu kapat",
"DG.DocumentController.calculatorTitle": "Hesap makinesi",
"DG.DocumentController.caseTableTitle": "Durum tablosu",
"DG.DocumentController.graphTitle": "Grafik",
"DG.DocumentController.sliderTitle": "Kaydırıcı",
"DG.DocumentController.textTitle": "Metin",
"DG.DocumentController.mapTitle": "Harita",
"DG.DocumentController.enterURLPrompt": "Görüntülenecek internet sayfasının URL'sini girin",
"DG.DocumentController.enterViewWebPageOKTip": "URL tarafından sağlanan internet sayfasından görüntüler",
"DG.Document.defaultDocumentName": "Başlıksız Dosya",
"DG.Document.documentName.toolTip": "Dosya adını düzenlemek için tıklayın",
"DG.SliderView.thumbView.toolTip": "Kaydırıcının değerini değiştirmek için sürükleyin",
"DG.SliderView.startButton.toolTip": "Animasyonu başlat/durdur",
"DG.ToolButtonData.tableButton.title": "Tablolar",
"DG.ToolButtonData.tableButton.toolTip": "Her veri için bir durum tablosu aç (ctrl-alt-t)",
"DG.ToolButtonData.graphButton.title": "Grafik",
"DG.ToolButtonData.graphButton.toolTip": "Grafik oluştur (ctrl-alt-g)",
"DG.ToolButtonData.sliderButton.title": "Kaydırıcı",
"DG.ToolButtonData.sliderButton.toolTip": "Kaydırıcı oluştur (ctrl-alt-s)",
"DG.ToolButtonData.calcButton.title": "Hesapla",
"DG.ToolButtonData.calcButton.toolTip": "Hesap makinesini aç/kapat (ctrl-alt-c)",
"DG.ToolButtonData.textButton.title": "Metin",
"DG.ToolButtonData.textButton.toolTip": "Bir metin nesnesi oluşturun (ctrl-alt-shift-t)",
"DG.ToolButtonData.mapButton.title": "Harita",
"DG.ToolButtonData.mapButton.toolTip": "Bir harita oluşturun",
"DG.ToolButtonData.optionMenu.title": "Seçenekler",
"DG.ToolButtonData.optionMenu.toolTip": "İnternet sayfasını görüntüle, rehberi yapılandır...",
"DG.ToolButtonData.tileListMenu.title": "Başlıklar",
"DG.ToolButtonData.tileListMenu.toolTip": "Dosyadaki başlıkların listesini göster",
"DG.ToolButtonData.guideMenu.title": "Rehber",
"DG.ToolButtonData.guideMenu.toolTip": "Rehberi bu aktivitede göster ve rehberde gezin",
"DG.ToolButtonData.guideMenu.showGuide": "Rehberi Göster",
"DG.ToolButtonData.help.title": "Yardım",
"DG.ToolButtonData.help.toolTip": "CODAP Destek, CODAP Projesi Hakkında",
"DG.Slider.multiples": "Çarpanları Sınırla:",
"DG.Slider.maxPerSecond": "Saniyedeki Maksimum Animasyon Karesi:",
"DG.Slider.direction": "Animasyon Yönü:",
"DG.Slider.backAndForth": "Geri ve İleri",
"DG.Slider.lowToHigh": "Düşükten Yükseğe",
"DG.Slider.highToLow": "Yüksekten Düşüğe",
"DG.Slider.mode": "Animasyon Tekrarı:",
"DG.Slider.nonStop": "Durmadan",
"DG.Slider.onceOnly": "Sadece bir kez",
"DG.Undo.exceptionOccurred": "Geri almaya çalışılırken bir hata oluştu.",
"DG.Redo.exceptionOccurred": "Yinelemeye çalışılırken bir hata oluştu.",
"DG.Undo.componentMove": "Bileşeni hareket ettirmeyi geri al",
"DG.Redo.componentMove": "Bileşeni hareket ettirmeyi yinele",
"DG.Undo.componentResize": "Bileşeni yeniden boyutlandırma işlemini geri al",
"DG.Redo.componentResize": "Bileşeni yeniden boyutlandırmayı yinele",
"DG.Undo.axisDilate": "Ekseni yeniden ölçeklendirmeyi geri al",
"DG.Redo.axisDilate": "Ekseni yeniden ölçeklendirmeyi yinele",
"DG.Undo.axisRescaleFromData": "Ekseni yeniden ölçeklendirmeyi geri al",
"DG.Redo.axisRescaleFromData": "Ekseni yeniden ölçeklendirmeyi yinele",
"DG.Undo.axisDrag": "Ekseni sürüklemeyi geri al",
"DG.Redo.axisDrag": "Ekseni sürüklemeyi yinele",
"DG.Undo.axisAttributeChange": "Eksen özelliğini değiştirmeyi geri al",
"DG.Redo.axisAttributeChange": "Eksen özelliğini değiştirmeyi yinele",
"DG.Undo.axisAttributeAdded": "Eksen özelliği eklemeyi geri al",
"DG.Redo.axisAttributeAdded": "Eksen özelliği eklemeyi yinele",
"DG.Undo.toggleComponent.add.calcView": "Hesap makinesini göstermeyi geri al",
"DG.Redo.toggleComponent.add.calcView": "Hesap makinesini göstermeyi yinele",
"DG.Undo.toggleComponent.delete.calcView": "Hesap makinesini gizleme işlemini geri al",
"DG.Redo.toggleComponent.delete.calcView": "Hesap makinesini gizleme işlemini yinele",
"DG.Undo.caseTable.open": "Durum tablolarını göstermeyi geri al",
"DG.Redo.caseTable.open": "Durum tablolarını göstermeyi yinele",
"DG.Undo.caseTable.editAttribute": "Durum tablosu özelliğini düzenleme işlemini geri al",
"DG.Redo.caseTable.editAttribute": "Durum tablosu özelliğini düzenleme işlemini yinele",
"DG.Undo.caseTable.createAttribute": "Durum tablosu özelliği oluşturmayı geri al",
"DG.Redo.caseTable.createAttribute": "Durum tablosu özelliği oluşturmayı yinele",
"DG.Undo.caseTable.editAttributeFormula": "Durum tablosu özellik formülünü düzenleme işlemini geri al",
"DG.Redo.caseTable.editAttributeFormula": "Durum tablosu özellik formülünü düzenleme işlemini yinele",
"DG.Undo.caseTable.editCellValue": "Durum tablosu hücre değerini düzenleme işlemini geri al",
"DG.Redo.caseTable.editCellValue": "Durum tablosu hücre değerini düzenleme işlemini yinele",
"DG.Undo.caseTable.sortCases": "Durumları sıralamayı geri al",
"DG.Redo.caseTable.sortCases": "Durumları sıralamayı yinele",
"DG.Undo.caseTable.deleteAttribute": "Durum tablosu özelliği silmeyi geri al",
"DG.Redo.caseTable.deleteAttribute": "Durum tablosu özelliği silmeyi yinele",
"DG.Undo.caseTable.createCollection": "Yeni koleksiyon oluşturmayı geri al",
"DG.Redo.caseTable.createCollection": "Yeni koleksiyon oluşturmayı yinele",
"DG.Undo.caseTable.collectionNameChange": "Koleksiyonu yeniden adlandırmayı geri al",
"DG.Redo.caseTable.collectionNameChange": "Koleksiyonu yeniden adlandırmayı yinele",
"DG.Undo.caseTable.createNewCase": "Yeni durum oluşturmayı geri al",
"DG.Redo.caseTable.createNewCase": "Yeni durum oluşturmayı yinele",
"DG.Undo.caseTable.insertCases": "Durum eklemeyi geri al",
"DG.Redo.caseTable.insertCases": "Durum eklemeyi yinele",
"DG.Undo.caseTable.groupToggleExpandCollapseAll": "Tabloları görüntüle/gizleyi geri al",
"DG.Redo.caseTable.groupToggleExpandCollapseAll": "Tabloları görüntüle/gizleyi yinele",
"DG.Undo.caseTable.expandCollapseOneCase": "Bir grubun genişleme veya yığılmasını geri al",
"DG.Redo.caseTable.expandCollapseOneCase": "Bir grubun genişleme veya yığılmasını yinele",
"DG.Undo.caseTable.resizeColumns": "Tüm sütunları otomatik olarak yeniden boyutlandırmayı geri al",
"DG.Redo.caseTable.resizeColumns": "Tüm sütunları otomatik olarak yeniden boyutlandırmayı yinele",
"DG.Undo.document.share": "Dosyayı paylaşmayı geri al",
"DG.Redo.document.share": "Dosyayı paylaşmayı yinele",
"DG.Undo.document.unshare": "Dosyayı paylaşımını durdurmayı geri al",
"DG.Redo.document.unshare": "Dosyayı paylaşımını durdurmayı yinele",
"DG.Undo.game.add": "Dosyaya oyun eklemeyi geri al",
"DG.Redo.game.add": "Dosyaya oyun eklemeyi yinele",
"DG.Undo.graph.showCount": "Sayımı gösteri geri al",
"DG.Redo.graph.showCount": "Sayımı gösteri yinele",
"DG.Undo.graph.hideCount": "Sayımı saklayı geri al",
"DG.Redo.graph.hideCount": "Sayımı saklayı yinele",
"DG.Undo.graph.showPercent": "Yüzdeleri gösteri geri al",
"DG.Redo.graph.showPercent": "Yüzdeleri gösteri yinele",
"DG.Undo.graph.hidePercent": "Yüzdeleri saklayı geri al",
"DG.Redo.graph.hidePercent": "Yüzdeleri saklayı yinele",
"DG.Undo.graph.showMovableLine": "Hareketli hattın gösterilmesini geri al",
"DG.Redo.graph.showMovableLine": "Hareketli hattın gösterilmesini yinele",
"DG.Undo.graph.hideMovableLine": "Hareketli hattın saklanmasını geri al",
"DG.Redo.graph.hideMovableLine": "Hareketli hattın saklanmasını yinele",
"DG.Undo.graph.lockIntercept": "Doğruların kesişimini kilitlemeyi geri al",
"DG.Redo.graph.lockIntercept": "Doğruların kesişimini kilitlemeyi yinele",
"DG.Undo.graph.unlockIntercept": "Doğruların kesişimi kilidini açmayı geri al",
"DG.Redo.graph.unlockIntercept": "Doğruların kesişimi kilidini açmayı yinele",
"DG.Undo.graph.showPlotFunction": "Çizilen fonksiyonu göstermeyi geri al",
"DG.Redo.graph.showPlotFunction": "Çizilen fonksiyonu göstermeyi yinele",
"DG.Undo.graph.hidePlotFunction": "Çizilen fonksiyonu saklamayı geri al",
"DG.Redo.graph.hidePlotFunction": "Çizilen fonksiyonu saklamayı yinele",
"DG.Undo.graph.changePlotFunction": "Çizilen fonksiyonu değiştirmeyi geri al",
"DG.Redo.graph.changePlotFunction": "Çizilen fonksiyonu değiştirmeyi yinele",
"DG.Undo.graph.showPlotValue": "Çizilen değeri göstermeyi geri al",
"DG.Redo.graph.showPlotValue": "Çizilen değeri göstermeyi yinele",
"DG.Undo.graph.hidePlotValue": "Çizilen değeri saklamayı geri al",
"DG.Redo.graph.hidePlotValue": "Çizilen değeri saklamayı yinele",
"DG.Undo.graph.changePlotValue": "Çizilen değeri değiştirmeyi geri al",
"DG.Redo.graph.changePlotValue": "Çizilen değeri değiştirmeyi yinele",
"DG.Undo.graph.showConnectingLine": "Bağlantı doğrusunu göstermeyi geri al",
"DG.Redo.graph.showConnectingLine": "Bağlantı doğrusunu göstermeyi yinele",
"DG.Undo.graph.hideConnectingLine": "Bağlantı doğrusunu saklamayı geri al",
"DG.Redo.graph.hideConnectingLine": "Bağlantı doğrusunu saklamayı yinele",
"DG.Undo.graph.showLSRL": "En küçük kareler çizgisini göstermeyi geri al",
"DG.Redo.graph.showLSRL": "En küçük kareler çizgisini göstermeyi yinele",
"DG.Undo.graph.hideLSRL": "En küçük kareler çizgisini saklamayı geri al",
"DG.Redo.graph.hideLSRL": "En küçük kareler çizgisini saklamayı yinele",
"DG.Undo.graph.showSquares": "Kareleri göstermeyi geri al",
"DG.Redo.graph.showSquares": "Kareleri göstermeyi yinele",
"DG.Undo.graph.hideSquares": "Kareleri saklamayı geri al",
"DG.Redo.graph.hideSquares": "Kareleri saklamayı yinele",
"DG.Undo.graph.showPlottedMean": "Ortalamayı göstermeyi geri al",
"DG.Redo.graph.showPlottedMean": "Ortalamayı göstermeyi yinele",
"DG.Undo.graph.hidePlottedMean": "Ortalamayı saklamayı geri al",
"DG.Redo.graph.hidePlottedMean": "Ortalamayı saklamayı yinele",
"DG.Undo.graph.showPlottedMedian": "Ortancayı göstermeyi geri al",
"DG.Redo.graph.showPlottedMedian": "Ortancayı göstermeyi yinele",
"DG.Undo.graph.hidePlottedMedian": "Ortancayı saklamayı geri al",
"DG.Redo.graph.hidePlottedMedian": "Ortancayı saklamayı yinele",
"DG.Undo.graph.showPlottedStDev": "Standart sapmayı göstermeyi geri al",
"DG.Redo.graph.showPlottedStDev": "Standart sapmayı göstermeyi yinele",
"DG.Undo.graph.hidePlottedStDev": "Standart sapmayı saklamayı geri al",
"DG.Redo.graph.hidePlottedStDev": "Standart sapmayı saklamayı yinele",
"DG.Undo.graph.showPlottedIQR": "Çeyrekler arası aralığı göstermeyi geri al",
"DG.Redo.graph.hidePlottedIQR": "Çeyrekler arası aralığı saklamayı yinele",
"DG.Undo.graph.hidePlottedIQR": "Çeyrekler arası aralığı saklamayı geri al",
"DG.Redo.graph.showPlottedIQR": "Çeyrekler arası aralığı göstermeyi yinele",
"DG.Undo.graph.addMovableValue": "Taşınabilir değer eklemeyi geri al",
"DG.Redo.graph.addMovableValue": "Taşınabilir değer eklemeyi yinele",
"DG.Undo.graph.removeMovableValue": "Taşınabilir değeri kaldırmayı geri al",
"DG.Redo.graph.removeMovableValue": "Taşınabilir değeri kaldırmayı yinele",
"DG.Undo.graph.moveMovableValue": "Taşınabilir değeri değiştirmeyi geri al",
"DG.Redo.graph.moveMovableValue": "Taşınabilir değeri değiştirmeyi yinele",
"DG.Undo.graph.changePointColor": "Verilerin rengini değiştirmeyi geri al",
"DG.Redo.graph.changePointColor": "Verilerin rengini değiştirmeyi yinele",
"DG.Undo.graph.changeStrokeColor": "Fırça rengini değiştirmeyi geri al",
"DG.Redo.graph.changeStrokeColor": "Fırça rengini değiştirmeyi yinele",
"DG.Undo.graph.changePointSize": "Nokta büyüklüğünü değiştirmeyi geri al",
"DG.Redo.graph.changePointSize": "Nokta büyüklüğünü değiştirmeyi yinele",
"DG.Undo.graph.changeAttributeColor": "Özellik rengini değiştirmeyi geri al",
"DG.Redo.graph.changeAttributeColor": "Özellik rengini değiştirmeyi yinele",
"DG.Undo.graph.changeBackgroundColor": "Grafik arka plan rengini değiştirmeyi geri al",
"DG.Redo.graph.changeBackgroundColor": "Grafik arka plan rengini değiştirmeyi yinele",
"DG.Undo.graph.toggleTransparent": "Grafik saydamlığını değiştirmeyi geri al",
"DG.Redo.graph.toggleTransparent": "Grafik saydamlığını değiştirmeyi yinele",
"DG.Undo.guide.show": "Rehberi göstermeyi geri al",
"DG.Redo.guide.show": "Rehberi göstermeyi yinele",
"DG.Undo.guide.navigate": "Rehber sayfasını değiştirmeyi geri al",
"DG.Redo.guide.navigate": "Rehber sayfasını değiştirmeyi yinele",
"DG.Undo.hideSelectedCases": "Seçili durumları gizlemeyi geri al",
"DG.Redo.hideSelectedCases": "Seçili durumları gizlemeyi yinele",
"DG.Undo.hideUnselectedCases": "Seçili olmayan durumları gizlemeyi geri al",
"DG.Redo.hideUnselectedCases": "Seçili olmayan durumları gizlemeyi yinele",
"DG.Undo.enableNumberToggle": "Ana Görünüm Ayarlarını Gösteri geri al",
"DG.Redo.enableNumberToggle": "Ana Görünüm Ayarlarını Gösteri yinele",
"DG.Undo.disableNumberToggle": "Ana Görünüm Ayarlarını gizlemeyi geri al",
"DG.Redo.disableNumberToggle": "Ana Görünüm Ayarlarını gizlemeyi yinele",
"DG.Undo.interactiveUndoableAction": "Etkileşimdeki bir eylemi geri al",
"DG.Redo.interactiveUndoableAction": "Etkileşimdeki bir eylemi yinele",
"DG.Undo.showAllCases": "Tüm durumları gösteri geri al",
"DG.Redo.showAllCases": "Tüm durumları gösteri yinele",
"DG.Undo.map.create": "Harita eklemeyi geri al",
"DG.Redo.map.create": "Harita eklemeyi yinele",
"DG.Undo.map.fitBounds": "Harita boyutlandırmayı geri al",
"DG.Redo.map.fitBounds": "Harita boyutlandırmayı yinele",
"DG.Undo.map.pan": "Haritada gezinmeyi geri al",
"DG.Redo.map.pan": "Haritada gezinmeyi yinele",
"DG.Undo.map.zoom": "Haritaya yakınlaşmayı geri al",
"DG.Redo.map.zoom": "Haritaya yakınlaşmayı yinele",
"DG.Undo.map.showGrid": "Haritada kareleri göstermeyi geri al",
"DG.Redo.map.showGrid": "Haritada kareleri göstermeyi yinele",
"DG.Undo.map.hideGrid": "Haritada kareleri gizlemeyi geri al",
"DG.Redo.map.hideGrid": "Haritada kareleri gizlemeyi yinele",
"DG.Undo.map.changeGridSize": "Harita karelerinin büyüklüğünü değiştirmeyi geri al",
"DG.Redo.map.changeGridSize": "Harita karelerinin büyüklüğünü değiştirmeyi yinele",
"DG.Undo.map.showPoints": "Haritada noktaları göstermeyi geri al",
"DG.Redo.map.showPoints": "Haritada noktaları göstermeyi yinele",
"DG.Undo.map.hidePoints": "Haritada noktaları gizlemeyi geri al",
"DG.Redo.map.hidePoints": "Haritada noktaları gizlemeyi yinele",
"DG.Undo.map.showLines": "Harita çizgilerini göstermeyi geri al",
"DG.Redo.map.showLines": "Harita çizgilerini göstermeyi yinele",
"DG.Undo.map.hideLines": "Harita çizgilerini gizlemeyi geri al",
"DG.Redo.map.hideLines": "Harita çizgilerini gizlemeyi yinele",
"DG.Undo.map.changeBaseMap": "Harita arka planını değiştirmeyi geri al",
"DG.Redo.map.changeBaseMap": "Harita arka planını değiştirmeyi yinele",
"DG.Undo.textComponent.create": "Bir metin objesi eklemeyi geri al",
"DG.Redo.textComponent.create": "Bir metin objesi eklemeyi yinele",
"DG.Undo.textComponent.edit": "Metni değiştirmeyi geri al",
"DG.Redo.textComponent.edit": "Metni değiştirmeyi yinele",
"DG.Undo.sliderComponent.create": "Kaydırıcı eklemeyi geri al",
"DG.Redo.sliderComponent.create": "Kaydırıcı eklemeyi yinele",
"DG.Undo.slider.change": "Kaydırıcı değeri değişimini geri al",
"DG.Redo.slider.change": "Kaydırıcı değeri değişimini yinele",
"DG.Undo.slider.changeMultiples": "Kaydırıcı katlarını değiştirmeyi geri al",
"DG.Redo.slider.changeMultiples": "Kaydırıcı katlarını değiştirmeyi yinele",
"DG.Undo.slider.changeSpeed": "Saniyedeki maksimum animasyon karesini değiştirmeyi geri al",
"DG.Redo.slider.changeSpeed": "Saniyedeki maksimum animasyon karesini değiştirmeyi yinele",
"DG.Undo.slider.changeDirection": "Kaydırıcı animasyon yönünü değiştirmeyi geri al",
"DG.Redo.slider.changeDirection": "Kaydırıcı animasyon yönünü değiştirmeyi yinele",
"DG.Undo.slider.changeRepetition": "Kaydırıcı animasyon tekrarını değiştirmeyi geri al",
"DG.Redo.slider.changeRepetition": "Kaydırıcı animasyon tekrarını değiştirmeyi yinele",
"DG.Undo.graphComponent.create": "Grafik eklemeyi geri al",
"DG.Redo.graphComponent.create": "Grafik eklemeyi yinele",
"DG.Undo.dataContext.create": "Bir veri seti oluşturmayı geri al",
"DG.Redo.dataContext.create": "Bir veri seti oluşturmayı yinele",
"DG.Undo.data.deleteCases": "Durumları silmeyi geri al",
"DG.Redo.data.deleteCases": "Durumları silmeyi yinele",
"DG.Undo.component.close": "Kapatma düğmesini geri al",
"DG.Redo.component.close": "Kapatma düğmesini yinele",
"DG.Undo.component.minimize": "Küçültme düğmesini geri al",
"DG.Redo.component.minimize": "Küçültme düğmesini yinele",
"DG.Undo.dataContext.moveAttribute": "Durum tablosu özelliğini değiştirmeyi geri al",
"DG.Redo.dataContext.moveAttribute": "Durum tablosu özelliğini değiştirmeyi yinele",
"DG.DataContext.singleCaseName": "Durum",
"DG.DataContext.pluralCaseName": "Durumlar",
"DG.DataContext.caseCountString": "%@1 %@2",
"DG.DataContext.setOfCasesLabel": "bir koleksiyon",
"DG.DataContext.collapsedRowString": "%@1 arasında %@2",
"DG.DataContext.noData": "Veri Yok",
"DG.DataContext.baseName": "Veri_Seti_%@1",
"DG.CollectionClient.cantEditFormulaErrorMsg": "\"% @\" özelliği için formül düzenlenemez.",
"DG.CollectionClient.cantEditFormulaErrorDesc": "Bir formül oluşturabilmek için yeni bir özellik tanımlayın.",
"DG.Formula.FuncCategoryArithmetic": "Aritmetik İşlemler",
"DG.Formula.FuncCategoryConversion": "Diğer İşlemler",
"DG.Formula.FuncCategoryDateTime": "Gün/Saat İşlemleri",
"DG.Formula.FuncCategoryLookup": "Arama İşlemleri",
"DG.Formula.FuncCategoryOther": "Diğer İşlemler",
"DG.Formula.FuncCategoryRandom": "Diğer İşlemler",
"DG.Formula.FuncCategoryStatistical": "İstatistiksel İşlemler",
"DG.Formula.FuncCategoryString": "Dizi İşlemleri",
"DG.Formula.FuncCategoryTrigonometric": "Trigonometrik İşlemler",
"DG.Formula.DateLongMonthJanuary": "Ocak",
"DG.Formula.DateLongMonthFebruary": "Şubat",
"DG.Formula.DateLongMonthMarch": "Mart",
"DG.Formula.DateLongMonthApril": "Nisan",
"DG.Formula.DateLongMonthMay": "Mayıs",
"DG.Formula.DateLongMonthJune": "Haziran",
"DG.Formula.DateLongMonthJuly": "Temmuz",
"DG.Formula.DateLongMonthAugust": "Ağustos",
"DG.Formula.DateLongMonthSeptember": "Eylül",
"DG.Formula.DateLongMonthOctober": "Ekim",
"DG.Formula.DateLongMonthNovember": "Kasım",
"DG.Formula.DateLongMonthDecember": "Aralık",
"DG.Formula.DateShortMonthJanuary": "Oca",
"DG.Formula.DateShortMonthFebruary": "Şub",
"DG.Formula.DateShortMonthMarch": "Mar",
"DG.Formula.DateShortMonthApril": "Nis",
"DG.Formula.DateShortMonthMay": "May",
"DG.Formula.DateShortMonthJune": "Haz",
"DG.Formula.DateShortMonthJuly": "Tem",
"DG.Formula.DateShortMonthAugust": "Ağu",
"DG.Formula.DateShortMonthSeptember": "Eyl",
"DG.Formula.DateShortMonthOctober": "Eki",
"DG.Formula.DateShortMonthNovember": "Kas",
"DG.Formula.DateShortMonthDecember": "Ara",
"DG.Formula.DateLongDaySunday": "Pazar",
"DG.Formula.DateLongDayMonday": "Pazartesi",
"DG.Formula.DateLongDayTuesday": "Salı",
"DG.Formula.DateLongDayWednesday": "Çarşamba",
"DG.Formula.DateLongDayThursday": "Perşembe",
"DG.Formula.DateLongDayFriday": "Cuma",
"DG.Formula.DateLongDaySaturday": "Cumartesi",
"DG.Utilities.date.localDatePattern": " (?:(?:[0-3]?\\d-(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\\d{2}(?:\\d{2})?)|(?:[01]?\\d/[0-3]?\\d/\\d{2}(?:\\d{2})?)) ",
"DG.Utilities.date.timePattern": "(?:[0-2]?\\d:[0-5]?\\d(?::[0-5]\\d(?:\\.\\d{3})?)? ?(?:[ap]m)?) ",
"DG.Utilities.date.iso8601Pattern": "^\\d{4}-[01]\\d-[0-3]\\d(?:[T ](?:[0-2]\\d:[0-5]\\d:[0-5]\\d(?:\\.\\d{3,6})?)(?:Z|(?:[-+]?[01]\\d:[0-5]\\d)|(?: ?[-+][0-2]\\d{3}))?)?$",
"DG.Utilities.colorPattern": "(?:rgb\\((?:\\d{1,3},){2}\\d{1,3}\\))|(?:rgba\\((?:\\d{1,3},){3}[\\d\\.]*\\))|(?:#[\\da-f]{6})",
"DG.Formula.SyntaxErrorMiddle": "Sözdizimi hatası: '%@'",
"DG.Formula.SyntaxErrorEnd": "Eksik ifade",
"DG.Formula.SyntaxErrorInvalidOperator": "Geçersiz operatör '%@'",
"DG.Formula.TypeError.name": "❌",
"DG.Formula.TypeError.message": "'%@' için geçersiz tür",
"DG.Formula.TypeError.description": "'%@' için geçersiz tür",
"DG.Formula.VarReferenceError.name": "❌",
"DG.Formula.VarReferenceError.message": "'%@' tanımlanamadı",
"DG.Formula.VarReferenceError.description": "'%@' değişkeni tanımlanamadı",
"DG.Formula.HierReferenceError.name": "❌",
"DG.Formula.HierReferenceError.message": "'%@' alt özelliği için geçersiz başvuru",
"DG.Formula.HierReferenceError.description": "'%@' bir alt özelliktir ve sadece toplu bir işlevde kullanılabilir.",
"DG.Formula.FuncReferenceError.name": "❌",
"DG.Formula.FuncReferenceError.message": "'%@()' tanımlanamadı",
"DG.Formula.FuncReferenceError.description": "'%@()' özelliği tanımlanamadı",
"DG.Formula.FuncArgsError.name": "❌",
"DG.Formula.FuncArgsErrorSingle.message": "'%@()' 1 değişken gerektiriyor",
"DG.Formula.FuncArgsErrorSingle.description": "'%@()' fonksiyonu 1 değişken gerektiriyor",
"DG.Formula.FuncArgsErrorPlural.message": "'%@()' gerektiriyor %@ değişken",
"DG.Formula.FuncArgsErrorPlural.description": "'%@()' fonksiyonu %@ değişken gerektiriyor",
"DG.Formula.FuncArgsErrorRange.message": "'%@()' gerektiriyor %@-%@ değişken",
"DG.Formula.FuncArgsErrorRange.description": "'%@()' fonksiyonu %@-%@ değişken gerektiriyor",
"DG.Formula.PendingRequest.name": "⌛",
"DG.Formula.PendingRequest.message": "Bekleyen istek...",
"DG.Formula.PendingRequest.description": "Bekleyen istek...",
"DG.Formula.FailedRequest.name": "❌",
"DG.Formula.FailedRequest.message": "İstek başarısız oldu (%@)",
"DG.Formula.FailedRequest.description": "İstek başarısız oldu (%@)",
"DG.Formula.PendingBoundaries.name": "⌛",
"DG.Formula.PendingBoundaries.message": "Sınırlar bekliyor...",
"DG.Formula.PendingBoundaries.description": "Sınırlar bekliyor...",
"DG.Formula.FailedBoundaries.name": "❌",
"DG.Formula.FailedBoundaries.message": "Sınırlar başarısız oldu (%@)",
"DG.Formula.FailedBoundaries.description": "Sınırlar başarısız oldu (%@)",
"DG.Formula.LookupDataSetError.message": "Tanınmayan veri seti: '%@'",
"DG.Formula.LookupDataSetError.description": "'%@' veri seti tanınmadı",
"DG.Formula.LookupAttrError.message": "'%@' bulunamadı '%@' veri setinin içinde",
"DG.Formula.LookupAttrError.description": "'%@' özelliği '%@' veri setinin içinde bulunamadı",
"DG.TableController.headerMenuItems.editAttribute": "Özellik Değerlerini Düzenle\n",
"DG.TableController.headerMenuItems.editFormula": "Formülü Düzenle",
"DG.TableController.headerMenuItems.randomizeAttribute": "Tekrar dağıt",
"DG.TableController.headerMenuItems.sortAscending": "Artan Şekilde Sırala (A→Z, 0→9)",
"DG.TableController.headerMenuItems.sortDescending": "Azalan Şekilde Sırala (9→0, Z→A)",
"DG.TableController.headerMenuItems.deleteAttribute": "Özelliği Sil",
"DG.TableController.newAttrDlg.defaultAttrName": "yeni_özellik",
"DG.TableController.newAttrDlg.attrNameHint": "Yeni özellik için bir ad girin",
"DG.TableController.newAttrDlg.formulaHint": "Bu özelliğin değerlerini hesaplamak için gerekiyorsa bir formül yazın",
"DG.TableController.newAttrDlg.applyTooltip": "Yeni özelliği ad ve formül (isteğe bağlı) kullanarak tanımlayın",
"DG.TableController.newAttrDlg.mustEnterAttrNameMsg": "Lütfen yeni özellik için bir ad girin",
"DG.TableController.newAttrDialog.AttributesCategory": "Özellikler",
"DG.TableController.newAttrDialog.SpecialCategory": "Özel",
"DG.TableController.newAttrDialog.GlobalsCategory": "Değerler",
"DG.TableController.newAttrDialog.ConstantsCategory": "Sabitler",
"DG.TableController.newAttrDialog.FunctionsCategory": "Fonksiyonlar",
"DG.TableController.renameAttributeInvalidMsg": "Özellik adları boş bırakılamaz",
"DG.TableController.renameAttributeInvalidDesc": "Lütfen geçerli bir özellik adı girin",
"DG.TableController.renameAttributeDuplicateMsg": "Aynı isimde bir özellik zaten var",
"DG.TableController.renameAttributeDuplicateDesc": "Lütfen yeni bir özellik adı girin",
"DG.TableController.deleteAttribute.confirmMessage": "Özelliği silin '%@'?",
"DG.TableController.deleteAttribute.confirmDescription": "Bu işlem geri alınamaz.",
"DG.TableController.deleteAttribute.okButtonTitle": "Özelliği Sil",
"DG.TableController.deleteAttribute.cancelButtonTitle": "İptal Et",
"DG.TableController.deleteDataSet.confirmMessage": "Bu veri setini sil ve yok et: '%@'?",
"DG.TableController.deleteDataSet.confirmDescription": "Bu işlem geri alınamaz.",
"DG.TableController.deleteDataSet.okButtonTitle": "Veri Setini Sil",
"DG.TableController.deleteDataSet.cancelButtonTitle": "İptal Et",
"DG.TableController.attrEditor.unitHint": "Varsa, ölçü birimi",
"DG.TableController.attrEditor.descriptionHint": "Özelliği tanımla",
"DG.TableController.setScoreDlg.applyTooltip": "'%@' özelliği için formülü ayarla",
"DG.TableController.setScoreDlg.formulaHint": "Bu niteliğin değerlerini hesaplamak için bir formül girin",
"DG.TableController.newAttributeTooltip": "Bu tabloya yeni bir özellik girin",
"DG.TableController.attributeEditor.title": "Özellik Değerleri",
"DG.CaseTableDropTarget.dropMessage": "Yeni bir koleksiyon oluşturmak için özelliği çıkarın",
"DG.CaseTable.defaultAttrName": "yeniÖzellik",
"DG.CaseTable.indexColumnName": "indeks",
"DG.CaseTable.indexColumnTooltip": "Koleksiyon içindeki sıra numarası (durumİndeksi)",
"DG.CaseTable.indexMenu.insertCase": "Durum Ekle",
"DG.CaseTable.indexMenu.insertCases": "Durumları Ekle...",
"DG.CaseTable.indexMenu.deleteCase": "Durumu Sil",
"DG.CaseTable.indexMenu.deleteCases": "Durumları Sil",
"DG.CaseTable.attribute.type.none": "\u200b",
"DG.CaseTable.attribute.type.nominal": "kategorik",
"DG.CaseTable.attribute.type.categorical": "kategorik",
"DG.CaseTable.attribute.type.numeric": "sayısal",
"DG.CaseTable.attribute.type.date": "tarih",
"DG.CaseTable.attribute.type.qualitative": "nitel",
"DG.CaseTable.attribute.type.boundary": "sınır",
"DG.CaseTable.attributeEditor.name": "isim",
"DG.CaseTable.attributeEditor.description": "açıklama",
"DG.CaseTable.attributeEditor.type": "tür",
"DG.CaseTable.attributeEditor.unit": "birim",
"DG.CaseTable.attributeEditor.precision": "kesinlik",
"DG.CaseTable.attributeEditor.editable": "düzenlenebilir",
"DG.CaseTable.insertCasesDialog.title": "Durum Ekle",
"DG.CaseTable.insertCasesDialog.numCasesPrompt": "# tane durum ekle:",
"DG.CaseTable.insertCasesDialog.beforeAfter.prompt": "yer:",
"DG.CaseTable.insertCasesDialog.beforeAfter.before": "önce",
"DG.CaseTable.insertCasesDialog.beforeAfter.after": "sonra",
"DG.CaseTable.insertCasesDialog.applyBtnTitle": "Durum Ekle",
"DG.CaseTable.insertCasesDialog.applyBtnTooltip": "Belirtilen sayıda durum ekle",
"DG.CaseTableController.allTables": "Tüm tablolar",
"DG.AttrFormView.attrNamePrompt": "Özellik adı:",
"DG.AttrFormView.formulaPrompt": "Formül:",
"DG.AttrFormView.operandMenuTitle": "--- Değer Ekle ---",
"DG.AttrFormView.functionMenuTitle": "--- Formül Ekle ---",
"DG.AttrFormView.applyBtnTitle": "Uygula",
"DG.AttrFormView.cancelBtnTitle": "İptal Et",
"DG.AttrFormView.cancelBtnTooltip": "Herhangi bir değişiklik yapmadan iletişim kutusunu kapat",
"DG.GuideConfigView.titlePrompt": "Rehber Başlığı",
"DG.GuideConfigView.titleHint": "Aktivite Adı",
"DG.GuideConfigView.itemTitleHint": "Bölüm Adı",
"DG.GuideConfigView.itemURLHint": "Bölümün URL'si",
"DG.GuideConfigView.okBtnTitle": "Tamam",
"DG.GuideConfigView.okBtnToolTip": "Rehber menü öğelerini kabul et",
"DG.GuideConfigView.cancelBtnTitle": "İptal et",
"DG.GuideConfigView.cancelBtnTooltip": "Herhangi bir değişiklik yapmadan iletişim kutusunu kapat",
"DG.GuideConfigView.httpWarning": "URL http:// veya https:// ile başlamalıdır",
"DG.DataDisplayModel.rescaleToData": "Verileri yeniden ölçeklendir",
"DG.DataDisplayModel.ShowConnectingLine": "Bağlantı Doğrularını Göster",
"DG.DataDisplayModel.HideConnectingLine": "Bağlantı Doğrularını Gizle",
"DG.AxisView.emptyGraphCue": "Burayı tıklayın, veya buraya bir özellik sürükleyin.",
"DG.CellLinearAxisView.midPanelTooltip": "Eksen ölçeğini çevirmek için sürükleyin",
"DG.CellLinearAxisView.lowerPanelTooltip": "Eksen alt sınırını değiştirmek için sürükleyin",
"DG.CellLinearAxisView.upperPanelTooltip": "Eksen üst sınırını değiştirmek için sürükleyin",
"DG.PlotModel.mixup": "Grafiği Karıştırın",
"DG.PlotModel.showCount": "Sayımı Göster",
"DG.PlotModel.hideCount": "Sayımı Gizle",
"DG.ScatterPlotModel.sumSquares": ",\nKareler toplamı = %@",
"DG.ScatterPlotModel.slopeOnly": "eğim = %@ %@",
"DG.ScatterPlotModel.yearsLabel": "Yılda",
"DG.ScatterPlotModel.daysLabel": "Günde",
"DG.ScatterPlotModel.hoursLabel": "Saatte",
"DG.ScatterPlotModel.minutesLabel": "Dakikada",
"DG.ScatterPlotModel.secondsLabel": "Saniyede",
"DG.LegendView.attributeTooltip": "Renklendirme özelliğini değiştirmek için tıklayın",
"DG.NumberToggleView.showAll": "Tümünü göster –",
"DG.NumberToggleView.hideAll": "Tümünü gizle –",
"DG.NumberToggleView.lastDash": "–",
"DG.NumberToggleView.lastUnchecked": "☐",
"DG.NumberToggleView.lastChecked": "☒",
"DG.NumberToggleView.lastLabel": "Son",
"DG.NumberToggleView.showAllTooltip": "Tüm durumları görmek için tıklayın\nGörünürlüğü değiştirmek için ana etiketlere tıklayın",
"DG.NumberToggleView.hideAllTooltip": "Tüm durumları gizlemek için tıklayın\nGörünürlüğü değiştirmek için ana etiketlere tıklayın",
"DG.NumberToggleView.enableLastModeTooltip": "Yalnızca son ana durumu görmek için tıklayın",
"DG.NumberToggleView.disableLastModeTooltip": "Son ana durum modundan çıkmak için tıklayın",
"DG.NumberToggleView.indexTooltip": "Görünürlüğü değiştirmek için tıklayın",
"DG.PlottedAverageAdornment.meanValueTitle": "ortalama=%@",
"DG.PlottedAverageAdornment.medianValueTitle": "ortanca=%@",
"DG.PlottedAverageAdornment.stDevValueTitle": "±1 SS, %@",
"DG.PlottedAverageAdornment.iqrValueTitle": "Çeyrekler açıklığı=%@",
"DG.PlottedAverageAdornment.boxPlotTitle": "alt=%@\nQ1=%@\nortalama=%@\nQ3=%@\nüst=%@\nçeyrekler açıklığı=%@",
"DG.PlottedCountAdornment.title": "%@ %@, %@%",
"DG.DataDisplayMenu.attribute_x": "X: %@",
"DG.DataDisplayMenu.attribute_y": "Y: %@",
"DG.DataDisplayMenu.attribute_y2": "Y: %@",
"DG.DataDisplayMenu.attribute_legend": "Renklendirme özelliği: %@",
"DG.DataDisplayMenu.remove": "Özelliği Çıkar",
"DG.DataDisplayMenu.removeAttribute_x": "X'i çıkar: %@",
"DG.DataDisplayMenu.removeAttribute_y": "Y'yi çıkar: %@",
"DG.DataDisplayMenu.removeAttribute_y2": "Y'yi çıkar: %@",
"DG.DataDisplayMenu.removeAttribute_legend": "Renklendirme özelliğini çıkar: %@",
"DG.DataDisplayMenu.treatAsCategorical": "Kategorik olarak değerlendir",
"DG.DataDisplayMenu.treatAsNumeric": "Sayısal olarak değerlendir",
"DG.DataDisplayMenu.hide": "Gizle ve Göster",
"DG.DataDisplayMenu.hideSelectedPlural": "Seçili Durumları Gizle",
"DG.DataDisplayMenu.hideUnselectedPlural": "Seçilmeyen Durumları Gizle",
"DG.DataDisplayMenu.hideSelectedSing": "Seçili Durumu Gizle",
"DG.DataDisplayMenu.hideUnselectedSing": "Seçilmeyen Durumu Gizle",
"DG.DataDisplayMenu.enableNumberToggle": "Ana Görünüm Ayarlarını Göster",
"DG.DataDisplayMenu.disableNumberToggle": "Ana Görünüm Ayarlarını Gizle",
"DG.DataDisplayMenu.showAll": "Tüm Durumları Göster",
"DG.DataDisplayMenu.snapshot": "Anlık Görüntü Al",
"DG.GraphView.replaceAttribute": "%@ değerini %@ ile değiştir",
"DG.GraphView.addAttribute": "%@ değerini ekle",
"DG.GraphView.addToEmptyPlace": "%@ ile eksen oluştur",
"DG.GraphView.addToEmptyX": "%@ ile X eksenini oluştur",
"DG.GraphView.dropInPlot": "Noktaları boya %@ değerleri için\n",
"DG.GraphView.zoomTip": "Yakınlaştırmak için çift tıklayın.\nUzaklaştırmak için Shift tuşunu basılı tutup çift tıklayın",
"DG.GraphView.rescale": "Verileri yeniden ölçeklendir",
"DG.AxisView.labelTooltip": "—%@ ekseni özelliğini değiştirmek için tıklayın",
"DG.AxisView.vertical": "dikey",
"DG.AxisView.horizontal": "yatay",
"DG.DataTip.connectingLine": "%@: %@\nile %@ %@",
"DG.MovableMonthYear": "%@, %@",
"DG.MovableMonthDayHour": "%@ %@ %@:00",
"DG.PlottedFormula.defaultNamePrompt": "Formül",
"DG.PlottedValue.namePrompt": "Çizilen Değer",
"DG.PlottedValue.formulaPrompt": "değer =",
"DG.PlottedValue.formulaHint": "\u200b",
"DG.PlottedFunction.namePrompt": "Çizilen Değer",
"DG.PlottedFunction.formulaPrompt": "f() =",
"DG.PlottedFunction.formulaHint": "Bir ifade yazın, örneğin x*x/30 - 50",
"DG.MapView.showGrid": "Kareleri Göster",
"DG.MapView.hideGrid": "Kareleri Gizle",
"DG.MapView.showPoints": "Puanları Göster",
"DG.MapView.hidePoints": "Puanları Gizle",
"DG.MapView.marqueeHint": "İşaretleme aracı—Haritadaki seçili noktaları sürükleyin",
"DG.MapView.gridControlHint": "Karelerin ölçüsünü değiştir",
"DG.Inspector.values": "Ölçüm",
"DG.Inspector.styles": "Biçimlendirme",
"DG.Inspector.pointSize": "Nokta büyüklüğü:",
"DG.Inspector.transparency": "Şeffaflık:",
"DG.Inspector.color": "Renk:",
"DG.Inspector.legendColor": "Renklendirmede kullanılacak renk:",
"DG.Inspector.backgroundColor": "Arka plan rengi:",
"DG.Inspector.stroke": "Çizgi:",
"DG.Inspector.rescale.toolTip": "Ekranı tüm verileri göstermek için yeniden ölçeklendirin",
"DG.Inspector.mixUp.toolTip": "Tüm noktaları karıştır",
"DG.Inspector.hideShow.toolTip": "Tüm durumları göster veya seçili/seçilmeyen durumları gizle",
"DG.Inspector.delete.toolTip": "Seçili/seçilmeyen durumları sil",
"DG.Inspector.sliderValues.toolTip": "Kaydırıcı animasyon yönünü, hızını ayarlayın ...\n",
"DG.Inspector.webViewEditURL.toolTip": "Görüntülenen web sayfasının URL'sini düzenleyin",
"DG.Inspector.selection.selectAll": "Tüm Durumları Seç",
"DG.Inspector.selection.deleteSelectedCases": "Seçili Durumları Sil",
"DG.Inspector.selection.deleteUnselectedCases": "Seçilmeyen Durumları Sil",
"DG.Inspector.deleteAll": "Tüm Durumları Sil",
"DG.Inspector.deleteDataSet": "Veri Setini Sil ve Yok Et",
"DG.Inspector.displayValues.toolTip": "Noktalarla birlikte gösterilenleri değiştirin",
"DG.Inspector.displayStyles.toolTip": "Ekran görünümünü değiştirin",
"DG.Inspector.makeImage.toolTip": "Resmi PNG dosyası olarak kaydet",
"DG.Inspector.displayShow": "Göster ...",
"DG.Inspector.colorPicker.more": "daha fazla",
"DG.Inspector.colorPicker.less": "daha az",
"DG.Inspector.graphTransparency": "Şeffaf",
"DG.Inspector.graphCount": "Sayı",
"DG.Inspector.graphPercent": "Yüzde",
"DG.Inspector.graphRow": "Satır",
"DG.Inspector.graphColumn": "Sütun",
"DG.Inspector.graphCell": "Hücre",
"DG.Inspector.graphConnectingLine": "Kesişen Doğrular",
"DG.Inspector.graphMovableLine": "Hareketli Doğru",
"DG.Inspector.graphInterceptLocked": "0 noktası Kilitli",
"DG.Inspector.graphPlottedFunction": "Çizilen Fonksiyon",
"DG.Inspector.graphSquares": "Kalanların Karesi",
"DG.Inspector.graphLSRL": "En Küçük Kareler Çizgisi",
"DG.Inspector.graphMovableValue": "Hareketli Değer",
"DG.Inspector.graphAdd": "Ekle",
"DG.Inspector.graphRemove": "Çıkar",
"DG.Inspector.graphPlottedMean": "Ortalama",
"DG.Inspector.graphPlottedMedian": "Ortanca",
"DG.Inspector.graphPlottedStDev": "Standart Sapma",
"DG.Inspector.graphPlottedIQR": "Çeyrekler Arası Aralık",
"DG.Inspector.graphPlottedBoxPlot": "Kutu Grafiği",
"DG.Inspector.graphPlottedValue": "Çizilen Değer",
"DG.Inspector.attributes.toolTip": "Yeni özellikler oluşturun. Durum verilerini dışa aktarın.",
"DG.Inspector.resize.toolTip": "Verilerin sığması için tüm sütunları yeniden boyutlandır",
"DG.Inspector.newAttribute": "Yeni Değer %@...",
"DG.Inspector.randomizeAllAttributes": "Hepsini yeniden dağıt",
"DG.Inspector.exportCaseData": "Durum Verilerini Dışa Aktar...",
"DG.Inspector.mapGrid": "Kareler",
"DG.Inspector.mapPoints": "Noktalar",
"DG.Inspector.mapLines": "Kesişen Doğrular",
"DG.GameController.continuityError": "Maalesef, durum tablosundaki sütunların sıralaması yapıldıktan sonra yeni veriler kabul edilemez.",
"DG.GameView.loading": "Yükleniyor",
"DG.GameView.loadError": "Bu metni görebiliyorsanız, yukarıdaki URL'yi yüklemek başarısız olmuş olabilir. Bağlantıyı başka bir tarayıcı sekmesinden kontrol edebilir veya hatayı http://codap.concord.org/help adresine tıklayarak bize bildirebilirsiniz.",
"DG.Component.closeComponent.confirmCloseMessage": "Emin misiniz?",
"DG.Component.closeComponent.confirmCloseDescription": "\u200b",
"DG.Component.closeComponent.okButtonTitle": "Evet, kapat",
"DG.Component.closeComponent.cancelButtonTitle": "İptal et",
"DG.GameController.confirmCloseDescription": "Bunu kapatırsanız, daha fazla veri ekleyemeyebilirsiniz.",
"DG.WebView.defaultTitle": "İnternet Sayfası",
"DG.mainPage.exceptionMessage": "An error has occurred that may affect how this program behaves. You may wish to reload this page after you save your work. (Error: %@)",
"DG.fileMenu.provider.examples.displayName": "Example Documents",
"DG.ToolButtonData.pluginMenu.title": "Plugins",
"DG.ToolButtonData.pluginMenu.toolTip": "Open a plugin component",
"DG.Undo.graph.showMovablePoint": "Undo showing movable point",
"DG.Redo.graph.showMovablePoint": "Redo showing movable point",
"DG.Undo.graph.hideMovablePoint": "Undo hiding movable point",
"DG.Redo.graph.hideMovablePoint": "Redo hiding movable point",
"DG.Undo.graph.moveMovablePoint": "Undo moving movable point",
"DG.Redo.graph.moveMovablePoint": "Redo moving movable point",
"DG.DataDisplayMenu.copyAsImage": "Open in Draw Tool",
"DG.DataDisplayMenu.exportImage": "Export Image...",
"DG.DataDisplayMenu.imageOfTitle": "Image of %@",
"DG.Inspector.graphMovablePoint": "Movable Point",
"DG.AppController.caseTableMenu.openCaseTableToolTip": "Open case table for this data set",
"DG.AppController.caseTableMenu.newDataSetToolTip": "Create a new data set",
"DG.AppController.caseTableMenu.deleteDataSetToolTip": "Delete and destroy this data set",
"DG.Undo.graph.showAsBarChart": "Undo fusing dots into bars",
"DG.Redo.graph.showAsBarChart": "Redo fusing dots into bars",
"DG.Undo.graph.showAsDotChart": "Undo dispersing bars into dots",
"DG.Redo.graph.showAsDotChart": "Redo dispersing bars into dots",
"DG.CountAxisView.countLabel": "Count",
"DG.CountAxisView.countLabelDescription": "Number of cases in the bar along this axis",
"DG.CountAxisView.percentLabel": "Percent",
"DG.CountAxisView.percentLabelDescription": "Percent of cases in the bar along this axis",
"DG.BarChartModel.cellTipPlural": "%@ of %@ %@ (%@%) are %@",
"DG.BarChartModel.cellTipSingular": "%@ of %@ %@ (%@%) is %@",
"DG.Inspector.configuration": "Configuration",
"DG.Inspector.displayConfiguration.toolTip": "Configure the display differently",
"DG.Inspector.displayScale": "Scale …",
"DG.Inspector.graphBarChart": "Fuse Dots into Bars",
"DG.Locale.name.de": "German",
"DG.Locale.name.en": "English",
"DG.Locale.name.es": "Spanish",
"DG.Locale.name.he": "Hebrew",
"DG.Locale.name.tr": "Turkish",
"DG.Locale.name.zh": "Traditional Chinese",
"DG.Undo.graph.swapCategories": "Undo reordering categories",
"DG.Redo.graph.swapCategories": "Redo reordering categories",
"DG.TableController.collectionTitleText": "%@1 (%@2 cases)",
"DG.TableController.collectionTitleTextWithSetAside": "%@1 (%@2 cases, %@3 set aside)",
"DG.Inspector.setaside.setAsideSelectedCases": "Set Aside Selected Cases",
"DG.Inspector.setaside.setAsideUnselectedCases": "Set Aside Unselected Cases",
"DG.Inspector.setaside.restoreSetAsideCases": "Restore %@ Set Aside Cases",
"DG.DocumentController.caseCardTitle": "Case Card",
"DG.DocumentController.toggleToCaseCard": "Switch to case card view of the data",
"DG.DocumentController.toggleToCaseTable": "Switch to case table view of the data",
"DG.CaseCard.indexString": "1 of %@ %@",
"DG.CaseCard.namePlusCaseCount": "%@ %@",
"DG.CaseCard.namePlusSelectionCount": "%@ selected of %@ %@",
"DG.CaseCard.summaryValues": "%@ values",
"DG.CaseCard.summaryRange": "%@–%@ %@",
"DG.CaseCard.navNextCase": "Select and show next case",
"DG.CaseCard.navPrevCase": "Select and show previous case",
"DG.CaseCard.navFirstCase": "Select and show first case",
"DG.CaseCard.navLastCase": "Select and show last case",
"DG.Undo.component.toggleTableToCard": "Undo changing case table to case card",
"DG.Redo.component.toggleTableToCard": "Redo changing case table to case card",
"DG.Undo.component.toggleCardToTable": "Undo changing case card to case table",
"DG.Redo.component.toggleCardToTable": "Redo changing case card to case table",
"DG.Undo.graph.addBackgroundImage": "Undo adding graph background image",
"DG.Redo.graph.addBackgroundImage": "Redo adding graph background image",
"DG.Undo.graph.removeBackgroundImage": "Undo removing graph background image",
"DG.Redo.graph.removeBackgroundImage": "Redo removing graph background image",
"DG.Undo.graph.lockBackgroundImage": "Undo locking background image to axes",
"DG.Redo.graph.lockBackgroundImage": "Redo locking background image to axes",
"DG.Undo.graph.unlockBackgroundImage": "Undo unlocking background image from axes",
"DG.Redo.graph.unlockBackgroundImage": "Redo unlocking background image from axes",
"DG.Undo.enableMeasuresForSelection": "Undo Show Measures For Selection",
"DG.Redo.enableMeasuresForSelection": "Redo Show Measures For Selection",
"DG.Undo.disableMeasuresForSelection": "Undo Hide Measures For Selection",
"DG.Redo.disableMeasuresForSelection": "Redo Hide Measures For Selection",
"DG.DataDisplayMenu.enableMeasuresForSelection": "Show Measures for Selection",
"DG.DataDisplayMenu.disableMeasuresForSelection": "Hide Measures for Selection",
"DG.DataDisplayMenu.addBackgroundImage": "Add Background Image",
"DG.DataDisplayMenu.lockImageToAxes": "Lock Background Image to Axes",
"DG.DataDisplayMenu.unlockImageFromAxes": "Unlock Background Image from Axes",
"DG.DataDisplayMenu.removeBackgroundImage": "Remove Background Image",
"DG.main.page.title": "%@1 - %@2",
"DG.TableController.headerMenuItems.deleteFormula": "Delete Formula (Keeping Values)",
"DG.TableController.headerMenuItems.recoverFormula": "Recover Deleted Formula",
"DG.Inspector.displayLayers.toolTip": "Change the appearance of the map layers",
"DG.Inspector.layers": "Layers",
"DG.Undo.graph.repositionEquation": "Undo repositioning equation",
"DG.Redo.graph.repositionEquation": "Redo repositioning equation",
"DG.TableController.attrEditor.precisionNumericHint": "Number of digits after decimal point",
"DG.TableController.attrEditor.precisionDateHint": "Determines how much of the date is displayed",
"DG.TableController.attrEditor.typeHint": "Set to force the attribute to be treated as a certain type",
"DG.TableController.attrEditor.nameHint": "The attribute name appears in the case table, case card, and on graph axes",
"DG.TableController.attrEditor.editableHint": "If the attribute is not editable, its values and/or formula cannot be changed",
"DG.CaseTable.attributeEditor.datePrecisionOptions": "year month day hour minute second millisecond",
"DG.AttributeFormat.DatePrecision.year": "YYYY",
"DG.AttributeFormat.DatePrecision.month": "MMM YYYY",
"DG.AttributeFormat.DatePrecision.day": "MMM D, YYYY",
"DG.AttributeFormat.DatePrecision.hour": "MMM D, YYYY HH:00",
"DG.AttributeFormat.DatePrecision.minute": "MMM D, YYYY HH:mm",
"DG.AttributeFormat.DatePrecision.second": "MMM D, YYYY HH:mm:ss",
"DG.CaseCard.attrHintPlain": "%@",
"DG.CaseCard.attrHintUnitsOnly": "%@1 in %@2",
"DG.CaseCard.attrHintDescription": "%@1: %@2",
"DG.CaseCard.attrHintFormula": "%@1 = %@2",
"DG.AppController.optionMenuItems.help-forum": "Help Forum...",
"DG.AppController.showHelpForumTitle": "Help Forum",
"DG.Locale.name.el": "Greek",
"DG.BarChartModel.cellTipNoLegendSingular": "%@ of %@ (%@%) is %@",
"DG.BarChartModel.cellTipNoLegendPlural": "%@ of %@ (%@%) are %@",
"DG.DataDisplayMenu.removeAttribute_top": "Remove Side-by-side Layout by %@",
"DG.DataDisplayMenu.removeAttribute_right": "Remove Vertical Layout by %@",
"DG.GraphView.layoutPlotsSideBySide": "Layout side-by-side by %@",
"DG.GraphView.layoutPlotsVertically": "Layout vertically by %@",
"DG.Undo.graph.makeStrokeSameAsFill": "Undo making stroke same as fill",
"DG.Redo.graph.makeStrokeSameAsFill": "Redo making stroke same as fill",
"DG.Undo.graph.makeStrokeIndependent": "Undo making stroke independent of fill",
"DG.Redo.graph.makeStrokeIndependent": "Redo making stroke independent of fill",
"DG.Inspector.strokeSameAsFill": "Stroke same color as fill",
"DG.Formula.DateShortDaySunday": "Sun",
"DG.Formula.DateShortDayMonday": "Mon",
"DG.Formula.DateShortDayTuesday": "Tue",
"DG.Formula.DateShortDayWednesday": "Wed",
"DG.Formula.DateShortDayThursday": "Thu",
"DG.Formula.DateShortDayFriday": "Fri",
"DG.Formula.DateShortDaySaturday": "Sat",
"DG.AttributeFormat.DatePrecision.millisecond": "MMM D, YYYY HH:mm:ss.SSS",
"DG.CellAxis.other": "OTHER",
"DG.PlottedAverageAdornment.madValueTitle": "±1 MAD, %@",
"DG.Inspector.graphPlottedMeanAbsDev": "Mean Absolute Deviation",
"DG.Undo.graph.showPlottedBoxPlot": "Undo showing box plot",
"DG.Redo.graph.hidePlottedBoxPlot": "Redo hiding box plot",
"DG.Undo.graph.hidePlottedBoxPlot": "Undo hiding box plot",
"DG.Redo.graph.showPlottedBoxPlot": "Redo showing box plot",
"DG.Undo.graph.showOutliers": "Undo showing outliers",
"DG.Redo.graph.hideOutliers": "Redo hiding outliers",
"DG.Undo.graph.hideOutliers": "Undo hiding outliers",
"DG.Redo.graph.showOutliers": "Redo showing outliers",
"DG.Inspector.graphBoxPlotShowOutliers": "Show Outliers",
"DG.Locale.name.nb": "Bokmål",
"DG.Locale.name.nn": "Nynorsk",
"DG.CaseCard.newCaseToolTip": "Add an empty case to this collection",
"DG.TableController.headerMenuItems.renameAttribute": "Rename",
"DG.Undo.graph.fuseDotsToRectangles": "Undo fusing dots into rectangles",
"DG.Redo.graph.fuseDotsToRectangles": "Redo fusing dots into rectangles",
"DG.Undo.graph.dissolveRectanglesToDots": "Undo dissolving rectangles into dots",
"DG.Redo.graph.dissolveRectanglesToDots": "Redo dissolving rectangles into dots",
"DG.Undo.graph.changeBreakdownType": "Undo changing scale type",
"DG.Redo.graph.changeBreakdownType": "Undo changing scale type",
"DG.Undo.graph.showAsBinnedPlot": "Undo grouping dots into bins",
"DG.Redo.graph.showAsBinnedPlot": "Redo grouping dots into bins",
"DG.Undo.graph.showAsDotPlot": "Undo ungrouping dots from bins",
"DG.Redo.graph.showAsDotPlot": "Redo ungrouping dots from bins",
"DG.Undo.graph.dragBinBoundary": "Undo dragging bin boundary",
"DG.Redo.graph.dragBinBoundary": "Redo dragging bin boundary",
"DG.Undo.graph.changeBinWidth": "Undo changing bin width",
"DG.Redo.graph.changeBinWidth": "Redo changing bin width",
"DG.Undo.graph.changeBinAlignment": "Undo changing bin alignment",
"DG.Redo.graph.changeBinAlignment": "Redo changing bin alignment",
"DG.BinnedPlotModel.dragBinTip": "Drag to change bin width",
"DG.HistogramView.barTipPlural": "%@ of %@ %@ (%@%) are ≥ %@ and < %@",
"DG.HistogramView.barTipSingular": "%@ of %@ %@ (%@%) is ≥ %@ and < %@",
"DG.HistogramView.barTipNoLegendSingular": "%@ of %@ (%@%) is ≥ %@ and < %@",
"DG.HistogramView.barTipNoLegendPlural": "%@ of %@ (%@%) are ≥ %@ and < %@",
"DG.Inspector.graphGroupIntoBins": "Group into Bins",
"DG.Inspector.graphBinWidth": "Bin width",
"DG.Inspector.graphAlignment": "Alignment",
"DG.CaseTable.dividerView.expandAllTooltip": "expand all groups",
"DG.CaseTable.dividerView.expandGroupTooltip": "expand group",
"DG.CaseTable.dividerView.collapseAllTooltip": "collapse all groups",
"DG.CaseTable.dividerView.collapseGroupTooltip": "collapse group",
"DG.BinnedPlotModel.binLabelTip": "Values in this bin are ≥ %@ and < %@",
"DG.Component.closeComponent.toolTip": "Close this Component",
"DG.Component.minimizeComponent.toolTip": "Minimize or expand this Component",
"DG.Locale.name.ja": "Japanese",
"DG.CaseCard.attrHintDescriptionAndFormula": "%@1: %@2\n%@1 = %@3",
"DG.Locale.name.zh-Hans": "Simplified Chinese",
"DG.PlottedCount.withoutSelection": "%@",
"DG.PlottedCount.withSelection": "%@ selected",
"DG.PlottedPercent.withoutSelection": "%@%",
"DG.PlottedPercent.withSelection": "%@% selected",
"DG.PlottedCountPercent.withoutSelection": "%@ (%@%)",
"DG.PlottedCountPercent.withSelection": "%@ of %@ (%@%) selected",
"DG.Undo.caseTable.resizeColumn": "Undo fit width to content",
"DG.Redo.caseTable.resizeColumn": "Redo fit width to content",
"DG.TableController.headerMenuItems.resizeColumn": "Fit width to content",
"DG.SelectedInfoView.infoPlural": "Showing measures for %@ selected cases",
"DG.SelectedInfoView.infoSing": "Showing measures for %@ selected case",
"DG.Inspector.copyCaseDataToClipboard": "Copy to Clipboard...",
"DG.Inspector.caseTable.exportCaseDialog.copyFrom": "Copy case data from:",
"DG.Inspector.caseTable.exportCaseDialog.copy": "Copy",
"DG.Inspector.caseTable.exportCaseDialog.copyTooltip": "Copy data to clipboard",
"DG.Inspector.caseTable.exportCaseDialog.copiedData": "Copied %@ to the clipboard",
"DG.Undo.caseTable.hideAttribute": "Undo hiding attribute",
"DG.Redo.caseTable.hideAttribute": "Redo hiding attribute",
"DG.Undo.caseTable.showAllHiddenAttributes": "Undo show all hidden attributes",
"DG.Redo.caseTable.showAllHiddenAttributes": "Redo show all hidden attributes",
"DG.TableController.headerMenuItems.hideAttribute": "Hide Attribute",
"DG.Inspector.attributes.showAllHiddenAttributesSing": "Show %@ Hidden Attribute",
"DG.Inspector.attributes.showAllHiddenAttributesPlural": "Show %@ Hidden Attributes",
"DG.Inspector.attributes.showAllHiddenAttributesDisabled": "Show Hidden Attributes",
"DG.Inspector.getCaseDataFromClipboard": "Import Case Data from Clipboard...",
"DG.CaseCard.addCaseButton": "add case",
"DG.Undo.DataContext.join": "Undo join of %@ to %@",
"DG.Redo.DataContext.join": "Redo join of %@ to %@",
"DG.Collection.joinTip": "Join %@ in %@ to %@ in %@ by matching %@ with %@",
"DG.Inspector.graphPlotPoints": "Points",
"DG.Inspector.graphBarForEachPoint": "Bar for Each Point",
"DG.Undo.graph.changeBarChartFunction": "Undo change bar chart formula",
"DG.Redo.graph.changeBarChartFunction": "Redo change bar chart formula",
"DG.Undo.graph.showAsLinePlot": "Undo bar for each point",
"DG.Redo.graph.showAsLinePlot": "Redo bar for each point",
"DG.Undo.graph.showAsStandardBarChart": "Undo using count or percent for bar chart scale",
"DG.Redo.graph.showAsStandardBarChart": "Redo using count or percent for bar chart scale",
"DG.Undo.graph.showAsComputedBarChart": "Undo computing bar length with formula",
"DG.Redo.graph.showAsComputedBarChart": "Redo computing bar length with formula",
"DG.FormulaAxisView.labelDescription": "The expression that determines the length of the bars. Click to edit.",
"DG.ComputedBarChartModel.cellTip": "For group %@ the value is %@",
"DG.BarChartFunction.namePrompt": "Bar Chart",
"DG.BarChartFunction.formulaPrompt": "bar length =",
"DG.BarChartFunction.formulaHint": "Type a formula to compute bar length",
"DG.BarChartFunction.emptyExpressionAxisPrompt": "Click here to provide a formula",
"DG.Inspector.graphFormula": "Formula",
"DG.Undo.displayOnlySelected": "Undo displaying only selected cases",
"DG.Redo.displayOnlySelected": "Redo displaying only selected cases",
"DG.Undo.webView.show": "Undo adding webView component",
"DG.Redo.webView.show": "Redo adding webView component",
"DG.Undo.imageComponent.show": "Undo adding image component",
"DG.Redo.imageComponent.show": "Redo adding image component",
"DG.DataDisplayMenu.displayOnlySelected": "Display Only Selected Cases",
"DG.DataDisplayMenu.displayingOnlySelected": "Displaying Only Selected Cases",
"DG.PlotBackgroundView.msg0": "This graph is set to display",
"DG.PlotBackgroundView.msg1": "only selected cases.",
"DG.PlotBackgroundView.msg2": "No cases are selected",
"DG.PlotBackgroundView.msg3": "so nothing is being displayed.",
"DG.PlotBackgroundView.msg4": "You can select cases in a",
"DG.PlotBackgroundView.msg5": "case table or another graph.",
"DG.ImageComponent.defaultTitle": "Image",
"DG.TableController.datasetMetadata.title": "Dataset Information",
"DG.CaseTable.datasetMetadata.url": "source",
"DG.CaseTable.datasetMetadata.creationDate": "import date",
"DG.TableController.datasetMetadata.descriptionHint": "Describe the dataset",
"DG.Inspector.datasetInfo.toolTip": "Display information about dataset",
"DG.CaseTable.indexMenu.moveEntryRow": "Move Data Entry Row Here",
"DG.CaseCard.deselect": "Deselect all cases",
"DG.CaseCard.noDeselect": "No cases are selected",
"DG.CaseTable.indexProto.tooltip": "Drag to place data entry row within this table",
"DG.AttributeFormat.DatePrecisionShort.year": "YYYY",
"DG.AttributeFormat.DatePrecisionShort.month": "M/YY",
"DG.AttributeFormat.DatePrecisionShort.day": "M/D/YY",
"DG.AttributeFormat.DatePrecisionShort.hour": "M/D/YY HH:00",
"DG.AttributeFormat.DatePrecisionShort.minute": "M/D/YY HH:mm",
"DG.AttributeFormat.DatePrecisionShort.second": "M/D/YY HH:mm:ss",
"DG.AttributeFormat.DatePrecisionShort.millisecond": "M/D/YY HH:mm:ss.SSS",
"DG.Formula.FuncCategoryLogic": "Logic Functions",
"DG.Undo.graph.showMeasureLabels": "Undo showing measure labels",
"DG.Redo.graph.showMeasureLabels": "Redo showing measure labels",
"DG.Undo.graph.hideMeasureLabels": "Undo hiding measure labels",
"DG.Redo.graph.hideMeasureLabels": "Redo hiding measure labels",
"DG.Inspector.showLabels": "Show Measure Labels",
"DG.Undo.caseTable.resizeOneColumn": "Undo resize column",
"DG.Redo.caseTable.resizeOneColumn": "Redo resize column",
"DG.CaseTable.attribute.type.checkbox": "checkbox",
"DG.AppController.caseTableMenu.clipboardDataset": "-- new from clipboard --",
"DG.AppController.caseTableMenu.clipboardDatasetToolTip": "Paste data set from clipboard",
"DG.AppController.optionMenuItems.toPrivacyPage": "Privacy Page..."
}); |
/**
* 活动评论表
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
/**
* _id 默认生成的唯一ID
* belongToId 关联活动ID(后面添加关联评论ID,嵌套评论)
* belongToUserId 关联用户ID
* belongToUsername 关联用户名
* headimgurl 关联用户头像
* content 评论内容
* createTime 创建时间
*/
var ActivityCommentSchema = new Schema({
belongToId: ObjectId,
belongToUserId: ObjectId,
belongToUsername: String,
headimgurl: String,
content: String,
createTime: {
type: Number,
default: 0
}
});
module.exports = mongoose.model('ActivityComment', ActivityCommentSchema, 'ck_activity_comments'); |
export function getMeta() {
return {
name: 'root',
component: 'Layout',
className: 'mk-app-my-setting',
children: [{
name: 'left',
component: 'Menu',
selectedKeys: '{{[data.other.selectedMenuItem]}}',
onSelect: '{{$menuSelected}}',
className: 'mk-app-my-setting-left',
children: [{
name: 'baseInfo',
component: 'Menu.Item',
key: 'baseInfo',
children: '个人资料'
}, {
name: 'security',
component: 'Menu.Item',
key: 'security',
children: '安全设置'
}]
}, {
name: 'baseInfo',
component: 'Layout',
className: 'mk-app-my-setting-baseInfo',
_visible: "{{data.other.selectedMenuItem == 'baseInfo'}}",
children: [{
name: 'title',
component: '::h1',
className: 'mk-app-my-setting-baseInfo-title',
children: '个人资料'
}, {
name: 'form',
component: 'Form',
className: 'mk-app-my-setting-baseInfo-form',
children: [{
name: 'photoItem',
component: 'Form.Item',
className: 'mk-app-my-setting-baseInfo-form-photo',
label: '头像',
required: true,
children: [{
name: 'container',
component: '::div',
children: [{
name: 'photo',
component: '::img',
src: '{{$getPhoto()}}'
}, {
name: 'upload',
component: 'Upload',
beforeUpload: '{{$upload}}',
children: '上传新照片'
}]
}]
}, {
name: 'mobileItem',
component: 'Form.Item',
label: '手机号',
required: true,
children: [{
name: 'mobile',
component: 'Input',
disabled: 'disabled',
value: '{{data.form.mobile}}',
}]
}, {
name: 'nicknameItem',
component: 'Form.Item',
label: '昵称',
required: true,
validateStatus: "{{data.other.error.nickname?'error':'success'}}",
help: '{{data.other.error.nickname}}',
children: [{
name: 'nickname',
component: 'Input',
onChange: "{{(e)=>$fieldChange('data.form.nickname', e.target.value)}}",
value: '{{data.form.nickname}}',
}]
}, {
name: 'sexItem',
component: 'Form.Item',
label: '性别',
required: true,
children: [{
name: 'sex',
component: 'Radio.Group',
value: '{{data.form.sex}}',
onChange: "{{(e)=>$sf('data.form.sex',e.target.value)}}",
children: [{
name: 'man',
value: '0',
component: 'Radio',
children: '男'
}, {
name: 'woman',
value: '1',
component: 'Radio',
children: '女'
}]
}]
}, {
name: 'birthdayItem',
component: 'Form.Item',
label: '出生日期',
children: [{
name: 'birthday',
component: 'DatePicker',
value: '{{$stringToMoment(data.form.birthday)}}',
onChange: "{{(d)=>$sf('data.form.birthday',$momentToString(d,'YYYY-MM-DD'))}}",
}]
}, {
name: 'saveItem',
component: 'Form.Item',
children: [{
name: 'save',
component: 'Button',
type: 'showy',
children: '保存',
style: { marginLeft: 115, marginTop: 7 },
onClick: '{{$saveBaseInfo}}'
}]
}]
}]
}, {
name: 'security',
component: 'Layout',
className: 'mk-app-my-setting-security',
_visible: "{{data.other.selectedMenuItem == 'security'}}",
children: [{
name: 'title',
component: '::h1',
className: 'mk-app-my-setting-baseInfo-title',
children: '安全设置'
}, {
name: 'level',
component: '::div',
className: '{{$getSecurityLevelClassName()}}',
children: [{
name: 'label',
component: '::e',
children: '密码安全级别:'
}, {
name: 'text',
component: '::span',
children: '{{$getSecurityLevelText()}}'
}, {
name: 'bar',
component: 'Progress',
percent: '{{data.form.securityLevel*20}}',
showInfo: false
}, {
name: 'modify',
component: 'Button',
type: 'softly',
size: 'small',
onClick:'{{$modifyPassword}}',
children: '修改密码',
}]
}]
}]
}
}
export function getInitState() {
return {
data: {
form: { sex: '1' },
other: {
selectedMenuItem: 'baseInfo',
error: {
}
}
}
}
} |
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(8899, 'localhost', function callback (err) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:8899');
});
|
// JavaScript Document
var datable_result;
var _url_path = baseurl+'times/new_times/';
var _url_del = baseurl+'times/delete/';
$(document).ready(function() {
datable_result = $('#datable_times').DataTable( {
"filter" : true,
"info" : true,
"paging" : true,
"ordering" : true,
"processing" : true,
"serverSide" : true ,
"bLengthChange" : false,
"bPaginate" : false,
"dom" : "<'row'<'col-sm-3'l><'col-sm-6'B><'col-sm-3'f>>tr<'col-sm-3'i>p",
buttons: [
{extend: 'copy',className: 'btn-sm'},
{extend: 'csv',title: 'ExampleFile', className: 'btn-sm'},
{extend: 'pdf', title: 'ExampleFile', className: 'btn-sm'},
{extend: 'print',className: 'btn-sm'},
{
text: 'Refresh', action: function () {
datable_result.draw();
}
}
],
"ajax" : {
"url" : baseurl+'times/times_data',
"type" : 'POST',
"destroy" : true
},
language: {
processing: _progImg,
loadingRecords: _progImg,
"url": baseurl+"assets/langs/kh.json"
},
"columns" : [
{ "data" : "times_name" },
{ "data" : "description" },
{ "data" : "status",
"fnCreatedCell" : function (nTd, sData, oData, iRow, iCol) {
var status = (oData.status==1)?'Active':'<font color="red">Inactive</font>';
$(nTd).html(status);
}
},
{ "data" : "id",
"fnCreatedCell" : function (nTd, sData, oData, iRow, iCol) {
$(nTd).html(
'<center>'+
'<a href="javascript:void(0);" class="label label-info" onclick="showAjaxModal(\''+_url_path+oData.id+'/edit/share\');"><i class="fa fa-pencil-square-o"></i></a> | '+
'<a href="#" class="label label-danger" onclick="on_delete_data(\''+_url_del+oData.id+'\');"><i class="fa fa-trash"></i></a>'+
'</center>');
}
}
],
"order": [[0, 'desc']]
});
} );
//
function on_delete_data(url){
delete_data(url,remove_row);
}
//
function remove_row(url){
$.ajax({
type: "POST",
url: url,
success: function(data){
datable_result.draw();
}
});
}
|
/*
* Copyright (c) $year, Den Norske Turistforening (DNT)
*
* https://github.com/Turistforeningen/turadmin
*/
define(function (require, exports, module) {
"use strict";
// Dependencies
var $ = require('jquery'),
Backbone = require('backbone'),
Template = require('text!templates/pictures/manager.html'),
PictureModel = require('models/picture'),
PictureEditView = require('views/pictures/edit'),
PictureCollection = require('collections/pictures'),
User = require('models/user'),
user = new User();
require('jquery-ui');
require('jquery.fileupload');
require('jquery.iframe-transport');
require('jquery.fileupload-process');
require('jquery.iframe-validate');
// Module
return Backbone.View.extend({
el: '[data-view="pictures-manager"]',
uploadUrl: 'https://jotunheimr.app.dnt.no/api/v1/upload',
// events: {
// 'picturesortstop': 'updateIndexes'
// },
defaults: {
// TODO: Document
},
messages: {
// TODO: Document
empty: 'Husk å legge inn bilder!',
info: '<strong>Hint!</strong> Du kan endre på rekkefølgen ved å dra i bildene. Det første bildet vil bli bruk som forsidebilde for turforslaget ditt på UT.no.'
},
events: {
// 'sortstop #route-pictures-all-container': 'picturePositionUpdated',
'updatePictureIndexes': 'updateIndexes'
},
initialize: function (options) {
// Set scope of methods to this view
_.bindAll(this, 'picturePositionUpdated', 'updateIndexes');
// If no picture collection is passed, create a new one
this.pictures = options.pictures || new PictureCollection();
// TODO: Map... Add some logic to set up a new map if one is not passed as an option
this.map = options.map;
this.pictures.on('remove', function () {
// Render view when all pictures are removed
if (this.pictures.length === 0) {
this.render();
}
}, this);
this.defaults = this.defaults || {};
if (typeof options.defaults === 'object') {
for (var defaultsKey in options.defaults) {
this.defaults[defaultsKey] = options.defaults[defaultsKey];
}
}
this.messages = this.messages || {};
if (typeof options.messages === 'object') {
for (var messagesKey in options.messages) {
this.messages[messagesKey] = options.messages[messagesKey];
}
}
},
appendPicture: function (picture) {
var pictureEditView = new PictureEditView({
model: picture,
map: this.map
}).render();
this.$('.message-empty').addClass('hidden');
this.$('[data-container-for="all-pictures-container"]').append(pictureEditView.el);
},
render: function () {
// Using Underscore we can compile our template with data
var data = {messages: this.messages};
var compiledTemplate = _.template(Template);
this.$el.html(compiledTemplate(data));
this.pictures.each(this.appendPicture, this);
this.setupFileupload();
if (this.pictures.length === 0) {
this.$('.message-empty').removeClass('hidden');
// this.$("#hintInfo").addClass("hidden");
} else {
this.$('.message-empty').addClass('hidden');
// this.$("#hintInfo").removeClass("hidden");
}
this.$errorContainer = $('[data-container-for="picture-upload-error"]');
this.$('[data-container-for="all-pictures-container"]').sortable({
items: '.picture.sortable',
placeholder: 'sortable-placeholder col-sm-4',
stop: $.proxy(this.onSortStop, this)
});
return this;
},
picturePositionUpdated: function (e, ui) {
// Trig event on ui-item so that the correct picture item listener is trigged.
// (In correct PictureEditView.js instance, which contains the model)
ui.item.trigger('pictureDropped', ui.item.index());
},
updateIndexes: function (e, picture, index) {
this.pictures.reIndex(picture, index);
},
onSortStop: function (e, ui) {
// Trig event on ui-item so that the correct picture item listener is trigged.
// (In correct PictureEditView.js instance, which contains the model)
ui.item.trigger('pictureDropped', ui.item.index());
// ui.item.trigger('picturesortstop', ui.item.index());
},
setupFileupload: function () {
var ended = false;
var that = this;
var fileUpload = this.$('#fileupload').fileupload({
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
sequentialUploads: true,
url: this.uploadUrl,
dataType: 'json',
maxFileSize: 6000000,
formData: [], // Prevent fileUpload from sending entire form, only send files
// Before sending file
submit: function (e, data) {
ended = false;
that.endProcessBar();
return true;
},
// Current file upload progress
progress: function (e, data) {
if (data.loaded === data.total) {
that.startProcessBar();
}
},
// Total upload progress
progressall: function (e, data) {
if (data.loaded === data.total) {
ended = true;
}
that.renderProgressBar(data);
},
// On response from server
done: function (e, data) {
that.endProcessBar();
if (ended) {
setTimeout(that.hideAndResetProgressBar, 1500);
}
that.addNewFile(data.result);
},
// On error
fail: function (e, data) {
Raven.captureException(e, {extra: {message: 'Picture upload failed',data: data}});
that.endProcessBar();
that.hideAndResetProgressBar();
that.addUploadError('En feil oppstod ved bildeopplasting. Du kan prøve igjen med et annet bilde.');
}
});
fileUpload.prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
fileUpload.on('fileuploadadd', function (e, data) {
that.resetUploadErrors();
});
fileUpload.on('fileuploadprocessfail', function (e, data) {
var errorMsg = '';
if ((data.files.length > 0) && (data.files.length === data.originalFiles.length)) {
if (data.files.length === 1) {
errorMsg = 'Bildet du forsøkte å laste opp var for stort eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
} else {
errorMsg = 'Bildene du forsøkte å laste opp var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
}
} else {
errorMsg = 'Et eller flere av bildene var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.. Bildene som ikke overstiger denne grensen blir lastet opp.';
}
that.addUploadError(errorMsg);
});
},
startProcessBar: function (data) {
this.$("#progress").addClass("progress-striped active");
this.$("#progress .progress-bar").html('<strong>Behandler bilde...</strong>');
},
endProcessBar: function (data) {
this.$("#progress .progress-bar").html('');
this.$($("#progress").removeClass("progress-striped active hidden"));
},
renderProgressBar: function (data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
this.$("#progress .progress-bar").css('width', progress + '%');
},
hideAndResetProgressBar: function () {
this.$($("#progress").addClass("hidden"));
this.$("#progress .progress-bar").css('width', 0);
},
addNewFile: function (file) {
var pictureData = this.defaults || {};
pictureData.img = file.versions;
pictureData.fotograf = {navn: user.get('navn'), epost: user.get('epost')};
if (!!file.meta && !!file.meta.geojson) {
pictureData.geojson = file.meta.geojson;
}
var picture = new PictureModel(pictureData);
this.pictures.add(picture);
this.appendPicture(picture);
this.$('#noPictures').addClass('hidden');
this.$('#hintInfo').removeClass('hidden');
},
addUploadError: function (err) {
var $error = $('<div class="alert alert-danger"></div>').text(err);
this.$errorContainer.append($error);
},
resetUploadErrors: function () {
this.$errorContainer.html('');
}
});
});
|
/*global define*/
define([
'./Cartesian3',
'./Cartographic',
'./defaultValue',
'./defined',
'./defineProperties',
'./DeveloperError',
'./Ellipsoid',
'./Math'
], function(
Cartesian3,
Cartographic,
defaultValue,
defined,
defineProperties,
DeveloperError,
Ellipsoid,
CesiumMath) {
'use strict';
function setConstants(ellipsoidGeodesic) {
var uSquared = ellipsoidGeodesic._uSquared;
var a = ellipsoidGeodesic._ellipsoid.maximumRadius;
var b = ellipsoidGeodesic._ellipsoid.minimumRadius;
var f = (a - b) / a;
var cosineHeading = Math.cos(ellipsoidGeodesic._startHeading);
var sineHeading = Math.sin(ellipsoidGeodesic._startHeading);
var tanU = (1 - f) * Math.tan(ellipsoidGeodesic._start.latitude);
var cosineU = 1.0 / Math.sqrt(1.0 + tanU * tanU);
var sineU = cosineU * tanU;
var sigma = Math.atan2(tanU, cosineHeading);
var sineAlpha = cosineU * sineHeading;
var sineSquaredAlpha = sineAlpha * sineAlpha;
var cosineSquaredAlpha = 1.0 - sineSquaredAlpha;
var cosineAlpha = Math.sqrt(cosineSquaredAlpha);
var u2Over4 = uSquared / 4.0;
var u4Over16 = u2Over4 * u2Over4;
var u6Over64 = u4Over16 * u2Over4;
var u8Over256 = u4Over16 * u4Over16;
var a0 = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0);
var a1 = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0);
var a2 = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0);
var a3 = (1.0 - 5.0 * u2Over4);
var distanceRatio = a0 * sigma - a1 * Math.sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * Math.sin(4.0 * sigma) * u4Over16 / 16.0 -
a3 * Math.sin(6.0 * sigma) * u6Over64 / 48.0 - Math.sin(8.0 * sigma) * 5.0 * u8Over256 / 512;
var constants = ellipsoidGeodesic._constants;
constants.a = a;
constants.b = b;
constants.f = f;
constants.cosineHeading = cosineHeading;
constants.sineHeading = sineHeading;
constants.tanU = tanU;
constants.cosineU = cosineU;
constants.sineU = sineU;
constants.sigma = sigma;
constants.sineAlpha = sineAlpha;
constants.sineSquaredAlpha = sineSquaredAlpha;
constants.cosineSquaredAlpha = cosineSquaredAlpha;
constants.cosineAlpha = cosineAlpha;
constants.u2Over4 = u2Over4;
constants.u4Over16 = u4Over16;
constants.u6Over64 = u6Over64;
constants.u8Over256 = u8Over256;
constants.a0 = a0;
constants.a1 = a1;
constants.a2 = a2;
constants.a3 = a3;
constants.distanceRatio = distanceRatio;
}
function computeC(f, cosineSquaredAlpha) {
return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0;
}
function computeDeltaLambda(f, sineAlpha, cosineSquaredAlpha, sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint) {
var C = computeC(f, cosineSquaredAlpha);
return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint +
C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0)));
}
function vincentyInverseFormula(ellipsoidGeodesic, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
var eff = (major - minor) / major;
var l = secondLongitude - firstLongitude;
var u1 = Math.atan((1 - eff) * Math.tan(firstLatitude));
var u2 = Math.atan((1 - eff) * Math.tan(secondLatitude));
var cosineU1 = Math.cos(u1);
var sineU1 = Math.sin(u1);
var cosineU2 = Math.cos(u2);
var sineU2 = Math.sin(u2);
var cc = cosineU1 * cosineU2;
var cs = cosineU1 * sineU2;
var ss = sineU1 * sineU2;
var sc = sineU1 * cosineU2;
var lambda = l;
var lambdaDot = CesiumMath.TWO_PI;
var cosineLambda = Math.cos(lambda);
var sineLambda = Math.sin(lambda);
var sigma;
var cosineSigma;
var sineSigma;
var cosineSquaredAlpha;
var cosineTwiceSigmaMidpoint;
do {
cosineLambda = Math.cos(lambda);
sineLambda = Math.sin(lambda);
var temp = cs - sc * cosineLambda;
sineSigma = Math.sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp);
cosineSigma = ss + cc * cosineLambda;
sigma = Math.atan2(sineSigma, cosineSigma);
var sineAlpha;
if (sineSigma === 0.0) {
sineAlpha = 0.0;
cosineSquaredAlpha = 1.0;
} else {
sineAlpha = cc * sineLambda / sineSigma;
cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha;
}
lambdaDot = lambda;
cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha;
if (isNaN(cosineTwiceSigmaMidpoint)) {
cosineTwiceSigmaMidpoint = 0.0;
}
lambda = l + computeDeltaLambda(eff, sineAlpha, cosineSquaredAlpha,
sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
} while (Math.abs(lambda - lambdaDot) > CesiumMath.EPSILON12);
var uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor);
var A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0;
var B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0;
var cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
var deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma *
(2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint *
(4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0);
var distance = minor * A * (sigma - deltaSigma);
var startHeading = Math.atan2(cosineU2 * sineLambda, cs - sc * cosineLambda);
var endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);
ellipsoidGeodesic._distance = distance;
ellipsoidGeodesic._startHeading = startHeading;
ellipsoidGeodesic._endHeading = endHeading;
ellipsoidGeodesic._uSquared = uSquared;
}
function computeProperties(ellipsoidGeodesic, start, end, ellipsoid) {
var firstCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(start, scratchCart2), scratchCart1);
var lastCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(end, scratchCart2), scratchCart2);
//>>includeStart('debug', pragmas.debug);
if (Math.abs(Math.abs(Cartesian3.angleBetween(firstCartesian, lastCartesian)) - Math.PI) < 0.0125) {
throw new DeveloperError('geodesic position is not unique');
}
//>>includeEnd('debug');
vincentyInverseFormula(ellipsoidGeodesic, ellipsoid.maximumRadius, ellipsoid.minimumRadius,
start.longitude, start.latitude, end.longitude, end.latitude);
ellipsoidGeodesic._start = Cartographic.clone(start, ellipsoidGeodesic._start);
ellipsoidGeodesic._end = Cartographic.clone(end, ellipsoidGeodesic._end);
ellipsoidGeodesic._start.height = 0;
ellipsoidGeodesic._end.height = 0;
setConstants(ellipsoidGeodesic);
}
var scratchCart1 = new Cartesian3();
var scratchCart2 = new Cartesian3();
/**
* Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points.
*
* @alias EllipsoidGeodesic
* @constructor
*
* @param {Cartographic} [start] The initial planetodetic point on the path.
* @param {Cartographic} [end] The final planetodetic point on the path.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies.
*/
function EllipsoidGeodesic(start, end, ellipsoid) {
var e = defaultValue(ellipsoid, Ellipsoid.WGS84);
this._ellipsoid = e;
this._start = new Cartographic();
this._end = new Cartographic();
this._constants = {};
this._startHeading = undefined;
this._endHeading = undefined;
this._distance = undefined;
this._uSquared = undefined;
if (defined(start) && defined(end)) {
computeProperties(this, start, end, e);
}
}
defineProperties(EllipsoidGeodesic.prototype, {
/**
* Gets the ellipsoid.
* @memberof EllipsoidGeodesic.prototype
* @type {Ellipsoid}
* @readonly
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
},
/**
* Gets the surface distance between the start and end point
* @memberof EllipsoidGeodesic.prototype
* @type {Number}
* @readonly
*/
surfaceDistance : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (!defined(this._distance)) {
throw new DeveloperError('set end positions before getting surfaceDistance');
}
//>>includeEnd('debug');
return this._distance;
}
},
/**
* Gets the initial planetodetic point on the path.
* @memberof EllipsoidGeodesic.prototype
* @type {Cartographic}
* @readonly
*/
start : {
get : function() {
return this._start;
}
},
/**
* Gets the final planetodetic point on the path.
* @memberof EllipsoidGeodesic.prototype
* @type {Cartographic}
* @readonly
*/
end : {
get : function() {
return this._end;
}
},
/**
* Gets the heading at the initial point.
* @memberof EllipsoidGeodesic.prototype
* @type {Number}
* @readonly
*/
startHeading : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (!defined(this._distance)) {
throw new DeveloperError('set end positions before getting startHeading');
}
//>>includeEnd('debug');
return this._startHeading;
}
},
/**
* Gets the heading at the final point.
* @memberof EllipsoidGeodesic.prototype
* @type {Number}
* @readonly
*/
endHeading : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (!defined(this._distance)) {
throw new DeveloperError('set end positions before getting endHeading');
}
//>>includeEnd('debug');
return this._endHeading;
}
}
});
/**
* Sets the start and end points of the geodesic
*
* @param {Cartographic} start The initial planetodetic point on the path.
* @param {Cartographic} end The final planetodetic point on the path.
*/
EllipsoidGeodesic.prototype.setEndPoints = function(start, end) {
//>>includeStart('debug', pragmas.debug);
if (!defined(start)) {
throw new DeveloperError('start cartographic position is required');
}
if (!defined(end)) {
throw new DeveloperError('end cartgraphic position is required');
}
//>>includeEnd('debug');
computeProperties(this, start, end, this._ellipsoid);
};
/**
* Provides the location of a point at the indicated portion along the geodesic.
*
* @param {Number} fraction The portion of the distance between the initial and final points.
* @returns {Cartographic} The location of the point along the geodesic.
*/
EllipsoidGeodesic.prototype.interpolateUsingFraction = function(fraction, result) {
return this.interpolateUsingSurfaceDistance(this._distance * fraction, result);
};
/**
* Provides the location of a point at the indicated distance along the geodesic.
*
* @param {Number} distance The distance from the inital point to the point of interest along the geodesic
* @returns {Cartographic} The location of the point along the geodesic.
*
* @exception {DeveloperError} start and end must be set before calling funciton interpolateUsingSurfaceDistance
*/
EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function(distance, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(this._distance)) {
throw new DeveloperError('start and end must be set before calling funciton interpolateUsingSurfaceDistance');
}
//>>includeEnd('debug');
var constants = this._constants;
var s = constants.distanceRatio + distance / constants.b;
var cosine2S = Math.cos(2.0 * s);
var cosine4S = Math.cos(4.0 * s);
var cosine6S = Math.cos(6.0 * s);
var sine2S = Math.sin(2.0 * s);
var sine4S = Math.sin(4.0 * s);
var sine6S = Math.sin(6.0 * s);
var sine8S = Math.sin(8.0 * s);
var s2 = s * s;
var s3 = s * s2;
var u8Over256 = constants.u8Over256;
var u2Over4 = constants.u2Over4;
var u6Over64 = constants.u6Over64;
var u4Over16 = constants.u4Over16;
var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 +
s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 -
(u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S -
(5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S -
29.0 * u8Over256 * cosine6S / 16.0) +
(u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S +
(5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S -
s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) +
(29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S +
539.0 * u8Over256 * sine8S / 1536.0;
var theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
var latitude = Math.atan(constants.a / constants.b * Math.tan(theta));
// Redefine in terms of relative argument of latitude.
sigma = sigma - constants.sigma;
var cosineTwiceSigmaMidpoint = Math.cos(2.0 * constants.sigma + sigma);
var sineSigma = Math.sin(sigma);
var cosineSigma = Math.cos(sigma);
var cc = constants.cosineU * cosineSigma;
var ss = constants.sineU * sineSigma;
var lambda = Math.atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading);
var l = lambda - computeDeltaLambda(constants.f, constants.sineAlpha, constants.cosineSquaredAlpha,
sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
if (defined(result)) {
result.longitude = this._start.longitude + l;
result.latitude = latitude;
result.height = 0.0;
return result;
}
return new Cartographic(this._start.longitude + l, latitude, 0.0);
};
return EllipsoidGeodesic;
});
|
import React from 'react';
import actions from '../actions';
import ChirpStore from '../stores/chirps';
import ChirpInput from './ChirpInput';
import ChirpList from './ChirpList';
import storeBind from '../mixins/store-bind';
const getState = () => ({chirps: ChirpStore.timeline()});
const Home = (props) => {
return (
<div>
<ChirpInput onSave={actions.chirp}/>
<ChirpList chirps={props.chirps}/>
</div>
);
};
export default storeBind(Home, [ChirpStore], getState);
|
/*
标准模板:弹出选择面板
注意,只需要修改搜索框和mini.DataGrid相关的列配置信息即可。
*/
ShipmentSelWindow = function () {
ShipmentSelWindow.superclass.constructor.apply(this, arguments);
}
mini.extend(ShipmentSelWindow, mini.BaseSelectWindow, {
keyLable: "出货单号:"
});
mini.regClass(ShipmentSelWindow, "shipmentselwindow"); |
'use strict';
describe('Dmaps E2E Tests:', function() {
describe('Test Dmaps page', function() {
it('Should not include new Dmaps', function() {
browser.get('http://localhost:3000/#!/dmaps');
expect(element.all(by.repeater('dmap in dmaps')).count()).toEqual(0);
});
});
});
|
var md5 = require("./md5")
var glob = require("glob")
var prepareRelay = require("./prepareRelay")
var prepareIsolatedFiles = require("./prepareIsolatedFiles")
var prepareProject = require("./prepareProject")
var generateJs = require("./outfileGenerators/js")
var generateJson = require("./outfileGenerators/json")
var JS_TYPE = "js";
var JSON_TYPE = "json";
var generators = {
[JS_TYPE]: generateJs,
[JSON_TYPE]: generateJson,
};
/**
* Generate a JavaScript client module based on local `.graphql` files.
*
* See {gatherOperations} and {generateClientCode} for options.
* @return {String} The generated JavaScript code
*/
function generateClient(options) {
var payload = gatherOperations(options)
var generatedCode = generateClientCode(options.client, payload.operations, options.clientType)
return generatedCode
}
/**
* Parse files in the specified path and generate an alias for each operation.
*
* @param {Object} options
* @param {String} options.path - A glob to recursively search for `.graphql` files (Default is `./`)
* @param {String} options.mode - If `"file"`, treat each file separately. If `"project"`, concatenate all files and extract each operation. If `"relay"`, treat it as relay-compiler output
* @param {Boolean} options.addTypename - Indicates if the "__typename" field are automatically added to your queries
* @param {String} options.clientType - The type of the generated code (i.e., json, js)
* @param {String} options.client - the Client ID that these operations belong to
* @param {Function} options.hash - A custom hash function for query strings with the signature `options.hash(string) => digest` (Default is `md5(string) => digest`)
* @param {Boolean} options.verbose - If true, print debug output
* @return {Array} Array of operations with name and alias
*/
function gatherOperations(options) {
var graphqlGlob = options.path || "./"
var hashFunc = options.hash || md5
var filesMode = options.mode || (graphqlGlob.indexOf("__generated__") > -1 ? "relay" : "project")
var addTypename = options.addTypename
var verbose = options.verbose
// Check for file ext already, add it if missing
var containsFileExt = graphqlGlob.indexOf(".graphql") > -1 || graphqlGlob.indexOf(".gql") > -1
if (!containsFileExt) {
graphqlGlob = graphqlGlob + "**/*.graphql*"
}
var payload = {
operations: []
}
var filenames = glob.sync(graphqlGlob, {})
if (verbose) {
console.log("[Sync] glob: ", graphqlGlob)
console.log("[Sync] " + filenames.length + " files:")
console.log(filenames.map(function(f) { return "[Sync] - " + f }).join("\n"))
}
if (filesMode == "relay") {
payload.operations = prepareRelay(filenames)
} else {
if (filesMode === "file") {
payload.operations = prepareIsolatedFiles(filenames, addTypename)
} else if (filesMode === "project") {
payload.operations = prepareProject(filenames, addTypename)
} else {
throw new Error("Unexpected mode: " + filesMode)
}
// Update the operations with the hash of the body
payload.operations.forEach(function(op) {
op.alias = hashFunc(op.body)
})
}
return payload
}
/**
* Given a map of { name => alias } pairs, generate outfile based on type.
* @param {String} clientName - the client ID that this map belongs to
* @param {Object} nameToAlias - `name => alias` pairs
* @param {String} type - the outfile's type
* @return {String} generated outfile code
*/
function generateClientCode(clientName, operations, type) {
if (!clientName) {
throw new Error("Client name is required to generate a persisted alias lookup map");
}
var nameToAlias = {}
operations.forEach(function(op) {
nameToAlias[op.name] = op.alias
})
// Build up the map
var keyValuePairs = "{"
keyValuePairs += Object.keys(nameToAlias).map(function(operationName) {
persistedAlias = nameToAlias[operationName]
return "\n \"" + operationName + "\": \"" + persistedAlias + "\""
}).join(",")
keyValuePairs += "\n}"
generateOutfile = generators[type || JS_TYPE];
if (!generateOutfile) {
throw new Error("Unknown generator type " + type + " encountered for generating the outFile");
}
return generateOutfile(type, clientName, keyValuePairs);
}
module.exports = {
generateClient,
generateClientCode,
gatherOperations,
JS_TYPE,
JSON_TYPE,
}
|
/**************************************************************************************
Aria Redirect action
Instruct Aria to fetch new instructions from a server and continue processing
with the result.
**************************************************************************************/
twimlActions.Redirect = function(command, callback) {
var call = command.call;
var channel = call.channel;
var client = call.client;
var playback = null;
console.log("Channel " + channel.id + " - Redirect: " + command.value);
// TODO: implement SMS message send
// go on to the next action
setTimeout(function() {
try {
var method = command.parameters.method || "POST";
var redirectURL = null;
if (command.value) {
var parts = url.parse(command.value);
if (parts.protocol) {
redirectURL = command.value;
} else {
redirectURL = url.resolve(call.baseUrl, command.value);
}
} else {
redirectURL = call.baseUrl;
}
var form = new formdata();
setCallData(call, form);
return fetchTwiml(method, redirectURL, call, form);
} catch (e) {
return callback();
}
}, 0);
};
|
class PassageGesture extends ShapeGesture {
existsAndHasConnections_(cell) {
return cell && cell.isKind(this.layer_, this.kind_) &&
cell.getLayerContent(this.layer_).hasOwnProperty(ck.connections);
}
populateCellMasks_(cell) {
this.cellMasks_ = new Map();
let centerMask = 0;
const top = cell.getNeighbor('top', cell.role != 'horizontal');
const right = cell.getNeighbor('right', cell.role != 'vertical');
const bottom = cell.getNeighbor('bottom', cell.role != 'horizontal');
const left = cell.getNeighbor('left', cell.role != 'vertical');
if (this.existsAndHasConnections_(top)) {
centerMask |= 1;
this.populateCellMask_(top, 4);
}
if (this.existsAndHasConnections_(right)) {
centerMask |= 2;
this.populateCellMask_(right, 8);
}
if (this.existsAndHasConnections_(bottom)) {
centerMask |= 4;
this.populateCellMask_(bottom, 1);
}
if (this.existsAndHasConnections_(left)) {
centerMask |= 8;
this.populateCellMask_(left, 2);
}
const topRight = cell.getNeighbor('top-right', cell.role == 'primary');
const bottomRight =
cell.getNeighbor('bottom-right', cell.role == 'primary');
const bottomLeft = cell.getNeighbor('bottom-left', cell.role == 'primary');
const topLeft = cell.getNeighbor('top-left', cell.role == 'primary');
if (this.existsAndHasConnections_(topRight)) {
centerMask |= 16;
this.populateCellMask_(topRight, 64);
}
if (this.existsAndHasConnections_(bottomRight)) {
centerMask |= 32;
this.populateCellMask_(bottomRight, 128);
}
if (this.existsAndHasConnections_(bottomLeft)) {
centerMask |= 64;
this.populateCellMask_(bottomLeft, 16);
}
if (this.existsAndHasConnections_(topLeft)) {
centerMask |= 128;
this.populateCellMask_(topLeft, 32);
}
if (cell.role == 'corner' && this.mode_ == 'adding') {
centerMask = 16;
this.populateCellMask_(top, 2 | 4 | 8);
this.populateCellMask_(topRight, 4 | 64 | 8);
this.populateCellMask_(right, 1 | 4 | 8);
this.populateCellMask_(bottomRight, 1 | 128 | 8);
this.populateCellMask_(bottom, 1 | 2 | 8);
this.populateCellMask_(bottomLeft, 1 | 16 | 2);
this.populateCellMask_(left, 1 | 2 | 4);
this.populateCellMask_(topLeft, 2 | 32 | 4);
}
this.populateCellMask_(cell, this.mode_ == 'removing' ? null : centerMask);
}
calcFinalCellValue_(cell, connections) {
if (cell.role == 'corner' && connections == 0) {
return null;
}
return super.calcFinalCellValue_(cell, connections);
}
populateCellMask_(cell, mask) {
if (cell && cell.hasLayerContent(this.layer_) &&
!cell.isKind(this.layer_, this.kind_)) {
return mask;
}
return super.populateCellMask_(cell, mask);
}
}
|
/*!
* mow
* Copyright(c) 2014 Shoota Kumano <shoota.dev@gmail.com>
* MIT Licensed
*/
'use strict'
var client = require('./client'),
util = require('./util'),
_ud =require('underscore');
// constructor
var mow = function(vendor){
if(! _ud.contains(this.SUPPORT_API, vendor)) return ;
this.client = new client(vendor);
};
module.exports = mow;
mow.prototype.SUPPORT_API = ['ATND', 'Doorkeeper', 'connpass', 'Zusaar'];
mow.prototype.toFindBy = function(key){
var result = this.result;
// TODO generate condition
};
mow.prototype.find = function(condition, callback){
var query = util.toQueryString(condition);
this.result = this.client.find(query, callback);
return this;
};
mow.prototype.findById = function(id, callback){
return this.find({event_id: id}, callback);
}; |
var _ = require('lodash');
var Configuration = require('./configuration');
var cryptoManager = require('./cryptoManager');
var settings = require('./configs/appconfig');
function Crypton(options) {
this._config = new Configuration(options, settings);
}
//Expose crypton public functions
Crypton.prototype.getConfig = function() {
return this._config.getOptions();
}
Crypton.prototype.init = function(options) {
this._config = new Configuration(options, settings);
}
/**
* Cipher a text with crypto. The operation is reversible
* @param {string} text
* @param {object} [options]
* @return {Promise<string>}
* @throws CipherCryptonError
*/
Crypton.prototype.cipher = function(text, options) {
return cryptoManager.cipher(text, options, this._config.getOptions());
}
/**
* Decipher a ciphered text with crypto
* @param {string} text
* @param {object} [options]
* @return {Promise<string>}
* @throws DecipherCryptonError
*/
Crypton.prototype.decipher = function(text, options) {
return cryptoManager.decipher(text, options, this._config.getOptions());
}
/**
* Check if the clear text matches with the ciphered text. If force is specified
* it accepts two ciphered strings to compare
* @param {string} text
* @param {string} ciphered
* @param {bool} force
* @param {options} [options]
* @return {Promise<bool>}
* @throws CompareCryptonError
*/
Crypton.prototype.compare = function(text, cipher, force, options) {
return cryptoManager.compare(text, cipher, force, options, this._config.getOptions());
}
/**
* Crypt a text with bcrypt. The operation is not reversible
* @param {string} text
* @param {object} [options]
* @return {Promise<string>}
* @throws EncryptCryptonError
*/
Crypton.prototype.crypt = function(text, options) {
return cryptoManager.crypt(text, options, this._config.getOptions());
}
/**
* Check if the clear text matches with the crypted text
* @param {string} text
* @param {string} crypted
* @return {Promise<bool>}
* @throws VerifyCryptonError
*/
Crypton.prototype.verify = function(text, crypted) {
return cryptoManager.verify(text, crypted, this._config.getOptions());
}
/**
* Get random bytes of a given length
* @param {int} length
* @param {string} [outputEncoding]
* @return {Promise<string>}
* @throws RandomBytesCryptonError
*/
Crypton.prototype.randomBytes = function(len, outputEncoding) {
return cryptoManager.randomBytes(len, outputEncoding, this._config.getOptions());
}
/**
* Get md5sum of a given string
* @param {string} data
* @param {string} [outputEncoding]
* @return {Promise<string>}
* @throws Md5CryptonError
*/
Crypton.prototype.md5 = function(data, outputEncoding) {
return cryptoManager.md5(data, outputEncoding, this._config.getOptions());
}
exports = module.exports.Crypton = Crypton;
exports = module.exports.create = function(options) {
return new Crypton(options);
};
|
'use strict';
app.factory('appointmentsService', ['$http', 'serverSettings', '$q', function ( $http, serverSettings, $q) {
var serviceBase = serverSettings.serviceBaseUri;
var appointmentsServiceFactory = {};
var _getAppointments4weeks = function (centerDate, calendarId) {
if(calendarId){
return $http.get(serviceBase + 'api/appointments/Get4Weeks/' + centerDate + '?CalendarId=' + calendarId).then(function (results) {
return results;
});
}else{
return $http.get(serviceBase + 'api/appointments/Get4Weeks/' + centerDate).then(function (results) {
return results;
});
}
};
var rangeCanceler;
var _getAppointmentsRange = function (startDate, endDate, calendarId) {
if (rangeCanceler)
rangeCanceler.resolve();
rangeCanceler = $q.defer();
if(calendarId){
return $http.get(serviceBase + 'api/appointments/GetFromRange/' + startDate + '/' + endDate + '?CalendarId=' + calendarId, {timeout: rangeCanceler.promise}).then(function (results) {
return results;
});
}else{
return $http.get(serviceBase + 'api/appointments/GetFromRange/' + startDate + '/' + endDate, {timeout: rangeCanceler.promise}).then(function (results) {
return results;
});
}
};
var _getAppointmentsByPatient = function (patientId) {
return $http.get(serviceBase + 'api/appointments/GetAppointmentsByPatient/' + patientId).then(function (results) {
return results;
});
};
var _postAppointment = function (_data) {
var data = getDTO(_data);
//When Patient object is empty server side is responding with error.
//Therefore if null check is true - removing the Patient object from the appointment object
if (data.Patient && !data.Patient.PatientName && !data.Patient.PhoneNumber)
delete data.Patient;
//If there is a phone num but not a patient name - make the patient name as phone number
if (data.Patient && data.Patient.PatientName == '' && data.Patient.PhoneNumber != '')
data.Patient.PatientName = data.Patient.PhoneNumber;
return $http.post(serviceBase + 'api/appointments', data).then(function (results) {
return results;
}/*,
function(error) {
return error;
}*/
);
};
var _deleteAppointment = function (data) {
return $http.delete(serviceBase + 'api/appointments/' + data.Id, data).then(function (results) {
return results;
}/*, function (error) {
var tmp = error;
console.error(error.statusText);
return error;
}*/);
};
var _putAppointment = function (_data) {
var data = getDTO(_data);
//When Patient object is empty server side is responding with error.
//Therefore if null check is true - removing the Patient object from the appointment object
if (!data.Patient.PatientName && !data.Patient.PhoneNumber)
delete data.Patient;
return $http.put(serviceBase + 'api/appointments/' + data.Id, data).then(function (results) {
return results;
}/*, function (error) {
var tmp = error;
console.error(error.statusText);
return error;
}*/);
};
var getDTO = function (obj) {
var dto = {};
angular.copy(obj, dto);
dto.Id = obj.id;
dto.StartDate = obj.start;
dto.EndDate = obj.end;
dto.AllDay = obj.allDay;
delete dto.source;
return dto;
};
appointmentsServiceFactory.getAppointmentsRange = _getAppointmentsRange;
appointmentsServiceFactory.getAppointments4weeks = _getAppointments4weeks;
appointmentsServiceFactory.getAppointmentsByPatient = _getAppointmentsByPatient;
appointmentsServiceFactory.postAppointment = _postAppointment;
appointmentsServiceFactory.deleteAppointment = _deleteAppointment;
appointmentsServiceFactory.putAppointment = _putAppointment;
return appointmentsServiceFactory;
}]); |
import DataType from 'sequelize';
import Model from '../sequelize'
import moment from 'moment';
const FBAuth = Model.define('FBAuth', {
id: {
type: DataType.INTEGER,
primaryKey: true,
},
accessToken: DataType.STRING,
expiresIn: {
type: DataType.DATE,
get: function() {
try {
return moment(new Date(this.getDataValue('expiresIn'))).format("YYYY/MM/DD HH:mm:SS");
} catch (e) {
}
}
},
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
export default FBAuth; |
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['245',"Tlece.Recruitment.ControllerApi Namespace","topic_00000000000000FA.html"],['246',"ApplicantController Class","topic_00000000000000FB.html"],['248',"Properties","topic_00000000000000FB_props--.html"]]; |
import Mixin from '@ember/object/mixin';
import propertyClassNameBinding from 'dummy/utils/property-class-name-binding';
export default Mixin.create({
classNameBindings: ['_depth', '_depthHover'],
depth: false,
_depth: propertyClassNameBinding('depth'),
depthHover: false,
_depthHover: propertyClassNameBinding('depthHover')
});
|
module.exports = {
siteMetadata: {
title: `Gatsby Benchmark Filters & Sort`,
description: `The filters and sort benchmark`,
author: `@gatsbyjs`,
},
flags: {
PARALLEL_QUERY_RUNNING: true,
}
// plugins: [`gatsby-plugin-benchmark-reporting`],
}
|
import test from 'ava';
import {Container, Descriptor} from '../src';
test('Container', t => {
const fooService = new Descriptor({service: 'foo-service'});
t.falsy(Container.has('foo-service'));
Container.register(fooService);
t.truthy(Container.has('foo-service'));
t.deepEqual(fooService, Container.get('foo-service'));
});
test('Container trying to receive non-Descriptor', t => {
t.false(Container.register({notDescriptor: true}));
});
|
var istanbul = require('browserify-istanbul');
var isparta = require('isparta');
module.exports = function (config) {
'use strict';
config.set({
browsers: [
//'PhantomJS',
'Chrome',
//'Firefox',
//'Safari',
//'Opera'
],
reporters: ['spec', 'notify', 'coverage'],
frameworks: ['browserify', 'mocha', 'chai'],
// list of files / patterns to load in the browser
files: ['./tests/spec/**/*.js'],
preprocessors: {
'./tests/spec/**/*.js': ['browserify']
},
client: {
mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter
},
browserify: {
debug: true,
transform: [
//'babelify',
istanbul({
instrumenter: isparta,
ignore: ['**/node_modules/**', '**/test/**']
})
],
configure: function (bundle) {
bundle.on('bundled', function (error) {
if (error != null)
console.error(error.message);
});
}
},
coverageReporter: {
reporters: [
{ type: 'lcovonly', subdir: '.', file: 'report-lcovonly.txt' },
{ type: 'text', subdir: '.', file: 'text.txt' },
{ type: 'text-summary', subdir: '.', file: 'text-summary.txt' },
]
},
notifyReporter: {
reportEachFailure: true,
reportSuccess: true
},
logLevel: config.LOG_INFO,
});
};
|
/* global __DEVTOOLS__ */
/*eslint-disable*/
import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import { Router } from 'react-router'
import configureStore from '../store/configureStore'
import routes from '../routes'
import defaultImport from '../utils/defaultImport'
/*eslint-enable*/
const store = configureStore()
function createElements (history) {
const elements = [
<Router key="router" history={history} children={routes} />
]
if (typeof __DEVTOOLS__ !== 'undefined' && __DEVTOOLS__) {
/*eslint-disable*/
const DevTools = defaultImport(require('./DevTools'))
/*eslint-enable*/
elements.push(<DevTools key="devtools" />)
}
return elements
}
export default class Root extends Component {
static propTypes = {
history: PropTypes.object.isRequired
};
render () {
return (
<Provider store={store} key="provider">
<div>
{createElements(this.props.history)}
</div>
</Provider>
)
}
}
|
'use strict';
var Command = require('./command');
var crypto = require('crypto');
var Promise = require('bluebird');
function Script(lua, numberOfKeys, keyPrefix) {
this.lua = lua;
this.sha = crypto.createHash('sha1').update(this.lua).digest('hex');
this.numberOfKeys = typeof numberOfKeys === 'number' ? numberOfKeys : null;
this.keyPrefix = keyPrefix ? keyPrefix : '';
}
Script.prototype.execute = function (container, args, options, callback) {
if (typeof this.numberOfKeys === 'number') {
args.unshift(this.numberOfKeys);
}
if (this.keyPrefix) {
options.keyPrefix = this.keyPrefix;
}
var evalsha = new Command('evalsha', [this.sha].concat(args), options);
evalsha.isCustomCommand = true;
var result = container.sendCommand(evalsha);
if (result instanceof Promise) {
var _this = this;
return result.catch(function (err) {
if (err.toString().indexOf('NOSCRIPT') === -1) {
throw err;
}
return container.sendCommand(new Command('eval', [_this.lua].concat(args), options));
}).nodeify(callback);
}
return result;
};
module.exports = Script;
|
export default 'SEND_REQUEST';
|
// jslint.js
// 2014-04-21
// Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
// 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 shall be used for Good, not Evil.
// 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.
// WARNING: JSLint will hurt your feelings.
// JSLINT is a global function. It takes two parameters.
// var myResult = JSLINT(source, option);
// The first parameter is either a string or an array of strings. If it is a
// string, it will be split on '\n' or '\r'. If it is an array of strings, it
// is assumed that each string represents one line. The source can be a
// JavaScript text or a JSON text.
// The second parameter is an optional object of options that control the
// operation of JSLINT. Most of the options are booleans: They are all
// optional and have a default value of false. One of the options, predef,
// can be an array of names, which will be used to declare global variables,
// or an object whose keys are used as global names, with a boolean value
// that determines if they are assignable.
// If it checks out, JSLINT returns true. Otherwise, it returns false.
// If false, you can inspect JSLINT.errors to find out the problems.
// JSLINT.errors is an array of objects containing these properties:
// {
// line : The line (relative to 0) at which the lint was found
// character : The character (relative to 0) at which the lint was found
// reason : The problem
// evidence : The text line in which the problem occurred
// raw : The raw message before the details were inserted
// a : The first detail
// b : The second detail
// c : The third detail
// d : The fourth detail
// }
// If a stopping error was found, a null will be the last element of the
// JSLINT.errors array. A stopping error means that JSLint was not confident
// enough to continue. It does not necessarily mean that the error was
// especially heinous.
// You can request a data structure that contains JSLint's results.
// var myData = JSLINT.data();
// It returns a structure with this form:
// {
// errors: [
// {
// line: NUMBER,
// character: NUMBER,
// reason: STRING,
// evidence: STRING
// }
// ],
// functions: [
// {
// name: STRING,
// line: NUMBER,
// level: NUMBER,
// parameter: [
// STRING
// ],
// var: [
// STRING
// ],
// exception: [
// STRING
// ],
// closure: [
// STRING
// ],
// outer: [
// STRING
// ],
// global: [
// STRING
// ],
// label: [
// STRING
// ]
// }
// ],
// global: [
// STRING
// ],
// member: {
// STRING: NUMBER
// },
// json: BOOLEAN
// }
// You can request a Function Report, which shows all of the functions
// and the parameters and vars that they use. This can be used to find
// implied global variables and other problems. The report is in HTML and
// can be inserted into an HTML <body>. It should be given the result of the
// JSLINT.data function.
// var myReport = JSLINT.report(data);
// You can request an HTML error report.
// var myErrorReport = JSLINT.error_report(data);
// You can obtain an object containing all of the properties found in the
// file. JSLINT.property contains an object containing a key for each
// property used in the program, the value being the number of times that
// property name was used in the file.
// You can request a properties report, which produces a list of the program's
// properties in the form of a /*properties*/ declaration.
// var myPropertyReport = JSLINT.properties_report(JSLINT.property);
// You can obtain the parse tree that JSLint constructed while parsing. The
// latest tree is kept in JSLINT.tree. A nice stringification can be produced
// with
// JSON.stringify(JSLINT.tree, [
// 'string', 'arity', 'name', 'first',
// 'second', 'third', 'block', 'else'
// ], 4));
// You can request a context coloring table. It contains information that can be
// applied to the file that was analyzed. Context coloring colors functions
// based on their nesting level, and variables on the color of the functions
// in which they are defined.
// var myColorization = JSLINT.color(data);
// It returns an array containing objects of this form:
// {
// from: COLUMN,
// thru: COLUMN,
// line: ROW,
// level: 0 or higher
// }
// JSLint provides three inline directives. They look like slashstar comments,
// and allow for setting options, declaring global variables, and establishing a
// set of allowed property names.
// These directives respect function scope.
// The jslint directive is a special comment that can set one or more options.
// For example:
/*jslint
evil: true, nomen: true, regexp: true, todo: true
*/
// The current option set is
// ass true, if assignment expressions should be allowed
// bitwise true, if bitwise operators should be allowed
// browser true, if the standard browser globals should be predefined
// closure true, if Google Closure idioms should be tolerated
// continue true, if the continuation statement should be tolerated
// debug true, if debugger statements should be allowed
// devel true, if logging should be allowed (console, alert, etc.)
// eqeq true, if == should be allowed
// evil true, if eval should be allowed
// forin true, if for in statements need not filter
// indent the indentation factor
// maxerr the maximum number of errors to allow
// maxlen the maximum length of a source line
// newcap true, if constructor names capitalization is ignored
// node true, if Node.js globals should be predefined
// nomen true, if names may have dangling _
// passfail true, if the scan should stop on first error
// plusplus true, if increment/decrement should be allowed
// properties true, if all property names must be declared with /*properties*/
// regexp true, if the . should be allowed in regexp literals
// rhino true, if the Rhino environment globals should be predefined
// unparam true, if unused parameters should be tolerated
// sloppy true, if the 'use strict'; pragma is optional
// stupid true, if really stupid practices are tolerated
// sub true, if all forms of subscript notation are tolerated
// todo true, if TODO comments are tolerated
// vars true, if multiple var statements per function should be allowed
// white true, if sloppy whitespace is tolerated
// The properties directive declares an exclusive list of property names.
// Any properties named in the program that are not in the list will
// produce a warning.
// For example:
/*properties
'\b', '\t', '\n', '\f', '\r', '!', '!=', '!==', '"', '%', '\'', '(begin)',
'(error)', '*', '+', '-', '/', '<', '<=', '==', '===', '>', '>=', '\\', a,
a_label, a_scope, already_defined, and, apply, arguments, arity, ass,
assign, assignment_expression, assignment_function_expression, at, avoid_a,
b, bad_assignment, bad_constructor, bad_in_a, bad_invocation, bad_new,
bad_number, bad_operand, bad_wrap, bitwise, block, break, breakage, browser,
c, call, charAt, charCodeAt, character, closure, code, color, combine_var,
comments, conditional_assignment, confusing_a, confusing_regexp,
constructor_name_a, continue, control_a, couch, create, d, dangling_a, data,
dead, debug, deleted, devel, disrupt, duplicate_a, edge, edition, elif,
else, empty_block, empty_case, empty_class, entityify, eqeq, error_report,
errors, evidence, evil, exception, exec, expected_a_at_b_c, expected_a_b,
expected_a_b_from_c_d, expected_id_a, expected_identifier_a,
expected_identifier_a_reserved, expected_number_a, expected_operator_a,
expected_positive_a, expected_small_a, expected_space_a_b,
expected_string_a, f, first, flag, floor, forEach, for_if, forin, from,
fromCharCode, fud, function, function_block, function_eval, function_loop,
function_statement, function_strict, functions, global, hasOwnProperty, id,
identifier, identifier_function, immed, implied_evil, indent, indexOf,
infix_in, init, insecure_a, isAlpha, isArray, isDigit, isNaN, join, jslint,
json, keys, kind, label, labeled, lbp, leading_decimal_a, led, left, length,
level, line, loopage, master, match, maxerr, maxlen, message, missing_a,
missing_a_after_b, missing_property, missing_space_a_b, missing_use_strict,
mode, move_invocation, move_var, n, name, name_function, nested_comment,
newcap, node, nomen, not, not_a_constructor, not_a_defined, not_a_function,
not_a_label, not_a_scope, not_greater, nud, number, octal_a, open, outer,
parameter, parameter_a_get_b, parameter_arguments_a, parameter_set_a,
params, paren, passfail, plusplus, pop, postscript, predef, properties,
properties_report, property, prototype, push, quote, r, radix, raw,
read_only, reason, redefinition_a_b, regexp, relation, replace, report,
reserved, reserved_a, rhino, right, scanned_a_b, scope, search, second,
shift, slash_equal, slice, sloppy, sort, split, statement, statement_block,
stop, stopping, strange_loop, strict, string, stupid, sub, subscript,
substr, supplant, sync_a, t, tag_a_in_b, test, third, thru, toString, todo,
todo_comment, token, tokens, too_long, too_many, trailing_decimal_a, tree,
unclosed, unclosed_comment, unclosed_regexp, unescaped_a, unexpected_a,
unexpected_char_a, unexpected_comment, unexpected_label_a,
unexpected_property_a, unexpected_space_a_b, unexpected_typeof_a,
uninitialized_a, unnecessary_else, unnecessary_initialize, unnecessary_use,
unparam, unreachable_a_b, unsafe, unused_a, url, use_array, use_braces,
use_nested_if, use_object, use_or, use_param, use_spaces, used,
used_before_a, var, var_a_not, var_loop, vars, varstatement, warn, warning,
was, weird_assignment, weird_condition, weird_new, weird_program,
weird_relation, weird_ternary, white, wrap, wrap_immediate, wrap_regexp,
write_is_wrong, writeable
*/
// The global directive is used to declare global variables that can
// be accessed by the program. If a declaration is true, then the variable
// is writeable. Otherwise, it is read-only.
// We build the application inside a function so that we produce only a single
// global variable. That function will be invoked immediately, and its return
// value is the JSLINT function itself. That function is also an object that
// can contain data and other functions.
var JSLINT = (function () {
'use strict';
function array_to_object(array, value) {
// Make an object from an array of keys and a common value.
var i, length = array.length, object = Object.create(null);
for (i = 0; i < length; i += 1) {
object[array[i]] = value;
}
return object;
}
var allowed_option = {
ass : true,
bitwise : true,
browser : true,
closure : true,
continue : true,
couch : true,
debug : true,
devel : true,
eqeq : true,
evil : true,
forin : true,
indent : 10,
maxerr : 1000,
maxlen : 256,
newcap : true,
node : true,
nomen : true,
passfail : true,
plusplus : true,
properties: true,
regexp : true,
rhino : true,
unparam : true,
sloppy : true,
stupid : true,
sub : true,
todo : true,
vars : true,
white : true
},
anonname, // The guessed name for anonymous functions.
// These are operators that should not be used with the ! operator.
bang = {
'<' : true,
'<=' : true,
'==' : true,
'===': true,
'!==': true,
'!=' : true,
'>' : true,
'>=' : true,
'+' : true,
'-' : true,
'*' : true,
'/' : true,
'%' : true
},
begin, // The root token
block_var, // vars defined in the current block
// browser contains a set of global names that are commonly provided by a
// web browser environment.
browser = array_to_object([
'clearInterval', 'clearTimeout', 'document', 'event', 'FormData',
'frames', 'history', 'Image', 'localStorage', 'location', 'name',
'navigator', 'Option', 'parent', 'screen', 'sessionStorage',
'setInterval', 'setTimeout', 'Storage', 'window', 'XMLHttpRequest'
], false),
// bundle contains the text messages.
bundle = {
a_label: "'{a}' is a statement label.",
a_scope: "'{a}' used out of scope.",
already_defined: "'{a}' is already defined.",
and: "The '&&' subexpression should be wrapped in parens.",
assignment_expression: "Unexpected assignment expression.",
assignment_function_expression: "Expected an assignment or " +
"function call and instead saw an expression.",
avoid_a: "Avoid '{a}'.",
bad_assignment: "Bad assignment.",
bad_constructor: "Bad constructor.",
bad_in_a: "Bad for in variable '{a}'.",
bad_invocation: "Bad invocation.",
bad_new: "Do not use 'new' for side effects.",
bad_number: "Bad number '{a}'.",
bad_operand: "Bad operand.",
bad_wrap: "Do not wrap function literals in parens unless they " +
"are to be immediately invoked.",
combine_var: "Combine this with the previous 'var' statement.",
conditional_assignment: "Expected a conditional expression and " +
"instead saw an assignment.",
confusing_a: "Confusing use of '{a}'.",
confusing_regexp: "Confusing regular expression.",
constructor_name_a: "A constructor name '{a}' should start with " +
"an uppercase letter.",
control_a: "Unexpected control character '{a}'.",
dangling_a: "Unexpected dangling '_' in '{a}'.",
deleted: "Only properties should be deleted.",
duplicate_a: "Duplicate '{a}'.",
empty_block: "Empty block.",
empty_case: "Empty case.",
empty_class: "Empty class.",
evil: "eval is evil.",
expected_a_b: "Expected '{a}' and instead saw '{b}'.",
expected_a_b_from_c_d: "Expected '{a}' to match '{b}' from line " +
"{c} and instead saw '{d}'.",
expected_a_at_b_c: "Expected '{a}' at column {b}, not column {c}.",
expected_id_a: "Expected an id, and instead saw #{a}.",
expected_identifier_a: "Expected an identifier and instead saw '{a}'.",
expected_identifier_a_reserved: "Expected an identifier and " +
"instead saw '{a}' (a reserved word).",
expected_number_a: "Expected a number and instead saw '{a}'.",
expected_operator_a: "Expected an operator and instead saw '{a}'.",
expected_positive_a: "Expected a positive number and instead saw '{a}'",
expected_small_a: "Expected a small positive integer and instead saw '{a}'",
expected_space_a_b: "Expected exactly one space between '{a}' and '{b}'.",
expected_string_a: "Expected a string and instead saw '{a}'.",
for_if: "The body of a for in should be wrapped in an if " +
"statement to filter unwanted properties from the prototype.",
function_block: "Function statements should not be placed in blocks." +
"Use a function expression or move the statement to the top of " +
"the outer function.",
function_eval: "The Function constructor is eval.",
function_loop: "Don't make functions within a loop.",
function_statement: "Function statements are not invocable. " +
"Wrap the whole function invocation in parens.",
function_strict: "Use the function form of 'use strict'.",
identifier_function: "Expected an identifier in an assignment " +
"and instead saw a function invocation.",
implied_evil: "Implied eval is evil. Pass a function instead of a string.",
infix_in: "Unexpected 'in'. Compare with undefined, or use the " +
"hasOwnProperty method instead.",
insecure_a: "Insecure '{a}'.",
isNaN: "Use the isNaN function to compare with NaN.",
leading_decimal_a: "A leading decimal point can be confused with a dot: '.{a}'.",
missing_a: "Missing '{a}'.",
missing_a_after_b: "Missing '{a}' after '{b}'.",
missing_property: "Missing property name.",
missing_space_a_b: "Missing space between '{a}' and '{b}'.",
missing_use_strict: "Missing 'use strict' statement.",
move_invocation: "Move the invocation into the parens that " +
"contain the function.",
move_var: "Move 'var' declarations to the top of the function.",
name_function: "Missing name in function statement.",
nested_comment: "Nested comment.",
not: "Nested not.",
not_a_constructor: "Do not use {a} as a constructor.",
not_a_defined: "'{a}' has not been fully defined yet.",
not_a_function: "'{a}' is not a function.",
not_a_label: "'{a}' is not a label.",
not_a_scope: "'{a}' is out of scope.",
not_greater: "'{a}' should not be greater than '{b}'.",
octal_a: "Don't use octal: '{a}'. Use '\\u....' instead.",
parameter_arguments_a: "Do not mutate parameter '{a}' when using 'arguments'.",
parameter_a_get_b: "Unexpected parameter '{a}' in get {b} function.",
parameter_set_a: "Expected parameter (value) in set {a} function.",
radix: "Missing radix parameter.",
read_only: "Read only.",
redefinition_a_b: "Redefinition of '{a}' from line {b}.",
reserved_a: "Reserved name '{a}'.",
scanned_a_b: "{a} ({b}% scanned).",
slash_equal: "A regular expression literal can be confused with '/='.",
statement_block: "Expected to see a statement and instead saw a block.",
stopping: "Stopping.",
strange_loop: "Strange loop.",
strict: "Strict violation.",
subscript: "['{a}'] is better written in dot notation.",
sync_a: "Unexpected sync method: '{a}'.",
tag_a_in_b: "A '<{a}>' must be within '<{b}>'.",
todo_comment: "Unexpected TODO comment.",
too_long: "Line too long.",
too_many: "Too many errors.",
trailing_decimal_a: "A trailing decimal point can be confused " +
"with a dot: '.{a}'.",
unclosed: "Unclosed string.",
unclosed_comment: "Unclosed comment.",
unclosed_regexp: "Unclosed regular expression.",
unescaped_a: "Unescaped '{a}'.",
unexpected_a: "Unexpected '{a}'.",
unexpected_char_a: "Unexpected character '{a}'.",
unexpected_comment: "Unexpected comment.",
unexpected_label_a: "Unexpected label '{a}'.",
unexpected_property_a: "Unexpected /*property*/ '{a}'.",
unexpected_space_a_b: "Unexpected space between '{a}' and '{b}'.",
unexpected_typeof_a: "Unexpected 'typeof'. " +
"Use '===' to compare directly with {a}.",
uninitialized_a: "Uninitialized '{a}'.",
unnecessary_else: "Unnecessary 'else' after disruption.",
unnecessary_initialize: "It is not necessary to initialize '{a}' " +
"to 'undefined'.",
unnecessary_use: "Unnecessary 'use strict'.",
unreachable_a_b: "Unreachable '{a}' after '{b}'.",
unsafe: "Unsafe character.",
unused_a: "Unused '{a}'.",
url: "JavaScript URL.",
use_array: "Use the array literal notation [].",
use_braces: "Spaces are hard to count. Use {{a}}.",
use_nested_if: "Expected 'else { if' and instead saw 'else if'.",
use_object: "Use the object literal notation {} or Object.create(null).",
use_or: "Use the || operator.",
use_param: "Use a named parameter.",
use_spaces: "Use spaces, not tabs.",
used_before_a: "'{a}' was used before it was defined.",
var_a_not: "Variable {a} was not declared correctly.",
var_loop: "Don't declare variables in a loop.",
weird_assignment: "Weird assignment.",
weird_condition: "Weird condition.",
weird_new: "Weird construction. Delete 'new'.",
weird_program: "Weird program.",
weird_relation: "Weird relation.",
weird_ternary: "Weird ternary.",
wrap_immediate: "Wrap an immediate function invocation in " +
"parentheses to assist the reader in understanding that the " +
"expression is the result of a function, and not the " +
"function itself.",
wrap_regexp: "Wrap the /regexp/ literal in parens to " +
"disambiguate the slash operator.",
write_is_wrong: "document.write can be a form of eval."
},
closure = array_to_object([
'goog'
], false),
comments,
comments_off,
couch = array_to_object([
'emit', 'getRow', 'isArray', 'log', 'provides', 'registerType',
'require', 'send', 'start', 'sum', 'toJSON'
], false),
descapes = {
'b': '\b',
't': '\t',
'n': '\n',
'f': '\f',
'r': '\r',
'"': '"',
'/': '/',
'\\': '\\',
'!': '!'
},
devel = array_to_object([
'alert', 'confirm', 'console', 'Debug', 'opera', 'prompt', 'WSH'
], false),
directive,
escapes = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\'': '\\\'',
'"' : '\\"',
'/' : '\\/',
'\\': '\\\\'
},
funct, // The current function
functions, // All of the functions
global_funct, // The global body
global_scope, // The global scope
in_block, // Where function statements are not allowed
indent,
itself, // JSLINT itself
json_mode,
lex, // the tokenizer
lines,
lookahead,
node = array_to_object([
'Buffer', 'clearImmediate', 'clearInterval', 'clearTimeout',
'console', 'exports', 'global', 'module', 'process',
'require', 'setImmediate', 'setInterval', 'setTimeout',
'__dirname', '__filename'
], false),
node_js,
numbery = array_to_object(['indexOf', 'lastIndexOf', 'search'], true),
next_token,
option,
predefined, // Global variables defined by option
prereg,
prev_token,
property,
protosymbol,
regexp_flag = array_to_object(['g', 'i', 'm'], true),
return_this = function return_this() {
return this;
},
rhino = array_to_object([
'defineClass', 'deserialize', 'gc', 'help', 'load', 'loadClass',
'print', 'quit', 'readFile', 'readUrl', 'runCommand', 'seal',
'serialize', 'spawn', 'sync', 'toint32', 'version'
], false),
scope, // An object containing an object for each variable in scope
semicolon_coda = array_to_object([';', '"', '\'', ')'], true),
// standard contains the global names that are provided by the
// ECMAScript standard.
standard = array_to_object([
'Array', 'Boolean', 'Date', 'decodeURI', 'decodeURIComponent',
'encodeURI', 'encodeURIComponent', 'Error', 'eval', 'EvalError',
'Function', 'isFinite', 'isNaN', 'JSON', 'Map', 'Math', 'Number',
'Object', 'parseInt', 'parseFloat', 'Promise', 'Proxy',
'RangeError', 'ReferenceError', 'Reflect', 'RegExp', 'Set',
'String', 'Symbol', 'SyntaxError', 'System', 'TypeError',
'URIError', 'WeakMap', 'WeakSet'
], false),
strict_mode,
syntax = Object.create(null),
token,
tokens,
var_mode,
warnings,
// Regular expressions. Some of these are stupidly long.
// carriage return, carriage return linefeed, or linefeed
crlfx = /\r\n?|\n/,
// unsafe characters that are silently deleted by one or more browsers
cx = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,
// identifier
ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/,
// javascript url
jx = /^(?:javascript|jscript|ecmascript|vbscript)\s*:/i,
// star slash
lx = /\*\/|\/\*/,
// characters in strings that need escapement
nx = /[\u0000-\u001f'\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
// sync
syx = /Sync$/,
// comment todo
tox = /^\W*to\s*do(?:\W|$)/i,
// token
tx = /^\s*([(){}\[\]\?.,:;'"~#@`]|={1,3}|\/(\*(jslint|properties|property|members?|globals?)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|[\^%]=?|&[&=]?|\|[|=]?|>{1,3}=?|<(?:[\/=!]|\!(\[|--)?|<=?)?|\!(\!|==?)?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+(?:[xX][0-9a-fA-F]+|\.[0-9]*)?(?:[eE][+\-]?[0-9]+)?)/;
if (typeof String.prototype.entityify !== 'function') {
String.prototype.entityify = function () {
return this
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
}
if (typeof String.prototype.isAlpha !== 'function') {
String.prototype.isAlpha = function () {
return (this >= 'a' && this <= 'z\uffff') ||
(this >= 'A' && this <= 'Z\uffff');
};
}
if (typeof String.prototype.isDigit !== 'function') {
String.prototype.isDigit = function () {
return (this >= '0' && this <= '9');
};
}
if (typeof String.prototype.supplant !== 'function') {
String.prototype.supplant = function (o) {
return this.replace(/\{([^{}]*)\}/g, function (a, b) {
var replacement = o[b];
return typeof replacement === 'string' ||
typeof replacement === 'number' ? replacement : a;
});
};
}
function sanitize(a) {
// Escapify a troublesome character.
return escapes[a] ||
'\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4);
}
function add_to_predefined(group) {
Object.keys(group).forEach(function (name) {
predefined[name] = group[name];
});
}
function assume() {
if (option.browser) {
add_to_predefined(browser);
option.browser = false;
}
if (option.closure) {
add_to_predefined(closure);
}
if (option.couch) {
add_to_predefined(couch);
option.couch = false;
}
if (option.devel) {
add_to_predefined(devel);
option.devel = false;
}
if (option.node) {
add_to_predefined(node);
option.node = false;
node_js = true;
}
if (option.rhino) {
add_to_predefined(rhino);
option.rhino = false;
}
}
// Produce an error warning.
function artifact(tok) {
if (!tok) {
tok = next_token;
}
return tok.id === '(number)' ? tok.number : tok.string;
}
function quit(message, line, character) {
throw {
name: 'JSLintError',
line: line,
character: character,
message: bundle.scanned_a_b.supplant({
a: bundle[message] || message,
b: Math.floor((line / lines.length) * 100)
})
};
}
function warn(code, line, character, a, b, c, d) {
var warning = { // ~~
id: '(error)',
raw: bundle[code] || code,
code: code,
evidence: lines[line - 1] || '',
line: line,
character: character,
a: a || artifact(this),
b: b,
c: c,
d: d
};
warning.reason = warning.raw.supplant(warning);
itself.errors.push(warning);
if (option.passfail) {
quit('stopping', line, character);
}
warnings += 1;
if (warnings >= option.maxerr) {
quit('too_many', line, character);
}
return warning;
}
function stop(code, line, character, a, b, c, d) {
var warning = warn(code, line, character, a, b, c, d);
quit('stopping', warning.line, warning.character);
}
function expected_at(at) {
if (!option.white && next_token.from !== at) {
next_token.warn('expected_a_at_b_c', '', at, next_token.from);
}
}
// lexical analysis and token construction
lex = (function lex() {
var character, c, from, length, line, pos, source_row;
// Private lex methods
function next_line() {
var at;
character = 1;
source_row = lines[line];
line += 1;
if (source_row === undefined) {
return false;
}
at = source_row.search(/\t/);
if (at >= 0) {
if (option.white) {
source_row = source_row.replace(/\t/g, ' ');
} else {
warn('use_spaces', line, at + 1);
}
}
at = source_row.search(cx);
if (at >= 0) {
warn('unsafe', line, at);
}
if (option.maxlen && option.maxlen < source_row.length) {
warn('too_long', line, source_row.length);
}
return true;
}
// Produce a token object. The token inherits from a syntax symbol.
function it(type, value) {
var id, the_token;
if (type === '(string)') {
if (jx.test(value)) {
warn('url', line, from);
}
}
the_token = Object.create(syntax[(
type === '(punctuator)' || (type === '(identifier)' &&
Object.prototype.hasOwnProperty.call(syntax, value))
? value
: type
)] || syntax['(error)']);
if (type === '(identifier)') {
the_token.identifier = true;
if (value === '__iterator__' || value === '__proto__') {
stop('reserved_a', line, from, value);
} else if (!option.nomen &&
(value.charAt(0) === '_' ||
value.charAt(value.length - 1) === '_')) {
warn('dangling_a', line, from, value);
}
}
if (type === '(number)') {
the_token.number = +value;
} else if (value !== undefined) {
the_token.string = String(value);
}
the_token.line = line;
the_token.from = from;
the_token.thru = character;
if (comments.length) {
the_token.comments = comments;
comments = [];
}
id = the_token.id;
prereg = id && (
('(,=:[!&|?{};~+-*%^<>'.indexOf(id.charAt(id.length - 1)) >= 0) ||
id === 'return' || id === 'case'
);
return the_token;
}
function match(x) {
var exec = x.exec(source_row), first;
if (exec) {
length = exec[0].length;
first = exec[1];
c = first.charAt(0);
source_row = source_row.slice(length);
from = character + length - first.length;
character += length;
return first;
}
for (;;) {
if (!source_row) {
if (!option.white) {
warn('unexpected_char_a', line, character - 1, '(space)');
}
return;
}
c = source_row.charAt(0);
if (c !== ' ') {
break;
}
source_row = source_row.slice(1);
character += 1;
}
stop('unexpected_char_a', line, character, c);
}
function string(x) {
var ch, at = 0, r = '', result;
function hex(n) {
var i = parseInt(source_row.substr(at + 1, n), 16);
at += n;
if (i >= 32 && i <= 126 &&
i !== 34 && i !== 92 && i !== 39) {
warn('unexpected_a', line, character, '\\');
}
character += n;
ch = String.fromCharCode(i);
}
if (json_mode && x !== '"') {
warn('expected_a_b', line, character, '"', x);
}
for (;;) {
while (at >= source_row.length) {
at = 0;
if (!next_line()) {
stop('unclosed', line - 1, from);
}
}
ch = source_row.charAt(at);
if (ch === x) {
character += 1;
source_row = source_row.slice(at + 1);
result = it('(string)', r);
result.quote = x;
return result;
}
if (ch < ' ') {
if (ch === '\n' || ch === '\r') {
break;
}
warn('control_a', line, character + at,
source_row.slice(0, at));
} else if (ch === '\\') {
at += 1;
character += 1;
ch = source_row.charAt(at);
switch (ch) {
case '':
warn('unexpected_a', line, character, '\\');
next_line();
at = -1;
break;
case '\'':
if (json_mode) {
warn('unexpected_a', line, character, '\\\'');
}
break;
case 'u':
hex(4);
break;
case 'v':
if (json_mode) {
warn('unexpected_a', line, character, '\\v');
}
ch = '\v';
break;
case 'x':
if (json_mode) {
warn('unexpected_a', line, character, '\\x');
}
hex(2);
break;
default:
if (typeof descapes[ch] !== 'string') {
warn(ch >= '0' && ch <= '7' ? 'octal_a' : 'unexpected_a',
line, character, '\\' + ch);
} else {
ch = descapes[ch];
}
}
}
r += ch;
character += 1;
at += 1;
}
}
function number(snippet) {
var digit;
if (source_row.charAt(0).isAlpha()) {
warn('expected_space_a_b',
line, character, c, source_row.charAt(0));
}
if (c === '0') {
digit = snippet.charAt(1);
if (digit.isDigit()) {
if (token.id !== '.') {
warn('unexpected_a', line, character, snippet);
}
} else if (json_mode && (digit === 'x' || digit === 'X')) {
warn('unexpected_a', line, character, '0x');
}
}
if (snippet.slice(snippet.length - 1) === '.') {
warn('trailing_decimal_a', line, character, snippet);
}
digit = +snippet;
if (!isFinite(digit)) {
warn('bad_number', line, character, snippet);
}
snippet = digit;
return it('(number)', snippet);
}
function comment(snippet, type) {
if (comments_off) {
warn('unexpected_comment', line, character);
} else if (!option.todo && tox.test(snippet)) {
warn('todo_comment', line, character);
}
comments.push({
id: type,
from: from,
thru: character,
line: line,
string: snippet
});
}
function regexp() {
var at = 0,
b,
bit,
depth = 0,
flag = '',
high,
letter,
low,
potential,
quote,
result;
for (;;) {
b = true;
c = source_row.charAt(at);
at += 1;
switch (c) {
case '':
stop('unclosed_regexp', line, from);
return;
case '/':
if (depth > 0) {
warn('unescaped_a', line, from + at, '/');
}
c = source_row.slice(0, at - 1);
potential = Object.create(regexp_flag);
for (;;) {
letter = source_row.charAt(at);
if (potential[letter] !== true) {
break;
}
potential[letter] = false;
at += 1;
flag += letter;
}
if (source_row.charAt(at).isAlpha()) {
stop('unexpected_a', line, from, source_row.charAt(at));
}
character += at;
source_row = source_row.slice(at);
quote = source_row.charAt(0);
if (quote === '/' || quote === '*') {
stop('confusing_regexp', line, from);
}
result = it('(regexp)', c);
result.flag = flag;
return result;
case '\\':
c = source_row.charAt(at);
if (c < ' ') {
warn('control_a', line, from + at, String(c));
} else if (c === '<') {
warn('unexpected_a', line, from + at, '\\');
}
at += 1;
break;
case '(':
depth += 1;
b = false;
if (source_row.charAt(at) === '?') {
at += 1;
switch (source_row.charAt(at)) {
case ':':
case '=':
case '!':
at += 1;
break;
default:
warn('expected_a_b', line, from + at,
':', source_row.charAt(at));
}
}
break;
case '|':
b = false;
break;
case ')':
if (depth === 0) {
warn('unescaped_a', line, from + at, ')');
} else {
depth -= 1;
}
break;
case ' ':
pos = 1;
while (source_row.charAt(at) === ' ') {
at += 1;
pos += 1;
}
if (pos > 1) {
warn('use_braces', line, from + at, pos);
}
break;
case '[':
c = source_row.charAt(at);
if (c === '^') {
at += 1;
if (!option.regexp) {
warn('insecure_a', line, from + at, c);
} else if (source_row.charAt(at) === ']') {
stop('unescaped_a', line, from + at, '^');
}
}
bit = false;
if (c === ']') {
warn('empty_class', line, from + at - 1);
bit = true;
}
klass: do {
c = source_row.charAt(at);
at += 1;
switch (c) {
case '[':
case '^':
warn('unescaped_a', line, from + at, c);
bit = true;
break;
case '-':
if (bit) {
bit = false;
} else {
warn('unescaped_a', line, from + at, '-');
bit = true;
}
break;
case ']':
if (!bit) {
warn('unescaped_a', line, from + at - 1, '-');
}
break klass;
case '\\':
c = source_row.charAt(at);
if (c < ' ') {
warn('control_a', line, from + at, String(c));
} else if (c === '<') {
warn('unexpected_a', line, from + at, '\\');
}
at += 1;
bit = true;
break;
case '/':
warn('unescaped_a', line, from + at - 1, '/');
bit = true;
break;
default:
bit = true;
}
} while (c);
break;
case '.':
if (!option.regexp) {
warn('insecure_a', line, from + at, c);
}
break;
case ']':
case '?':
case '{':
case '}':
case '+':
case '*':
warn('unescaped_a', line, from + at, c);
break;
}
if (b) {
switch (source_row.charAt(at)) {
case '?':
case '+':
case '*':
at += 1;
if (source_row.charAt(at) === '?') {
at += 1;
}
break;
case '{':
at += 1;
c = source_row.charAt(at);
if (c < '0' || c > '9') {
warn('expected_number_a', line,
from + at, c);
}
at += 1;
low = +c;
for (;;) {
c = source_row.charAt(at);
if (c < '0' || c > '9') {
break;
}
at += 1;
low = +c + (low * 10);
}
high = low;
if (c === ',') {
at += 1;
high = Infinity;
c = source_row.charAt(at);
if (c >= '0' && c <= '9') {
at += 1;
high = +c;
for (;;) {
c = source_row.charAt(at);
if (c < '0' || c > '9') {
break;
}
at += 1;
high = +c + (high * 10);
}
}
}
if (source_row.charAt(at) !== '}') {
warn('expected_a_b', line, from + at,
'}', c);
} else {
at += 1;
}
if (source_row.charAt(at) === '?') {
at += 1;
}
if (low > high) {
warn('not_greater', line, from + at,
low, high);
}
break;
}
}
}
c = source_row.slice(0, at - 1);
character += at;
source_row = source_row.slice(at);
return it('(regexp)', c);
}
// Public lex methods
return {
init: function (source) {
if (typeof source === 'string') {
lines = source.split(crlfx);
} else {
lines = source;
}
line = 0;
next_line();
from = 1;
},
// token -- this is called by advance to get the next token.
token: function () {
var first, i, snippet;
for (;;) {
while (!source_row) {
if (!next_line()) {
return it('(end)');
}
}
snippet = match(tx);
if (snippet) {
// identifier
first = snippet.charAt(0);
if (first.isAlpha() || first === '_' || first === '$') {
return it('(identifier)', snippet);
}
// number
if (first.isDigit()) {
return number(snippet);
}
switch (snippet) {
// string
case '"':
case "'":
return string(snippet);
// // comment
case '//':
comment(source_row, '//');
source_row = '';
break;
// /* comment
case '/*':
for (;;) {
i = source_row.search(lx);
if (i >= 0) {
break;
}
character = source_row.length;
comment(source_row);
from = 0;
if (!next_line()) {
stop('unclosed_comment', line, character);
}
}
comment(source_row.slice(0, i), '/*');
character += i + 2;
if (source_row.charAt(i) === '/') {
stop('nested_comment', line, character);
}
source_row = source_row.slice(i + 2);
break;
case '':
break;
// /
case '/':
if (token.id === '/=') {
stop('slash_equal', line, from);
}
return prereg
? regexp()
: it('(punctuator)', snippet);
// punctuator
default:
return it('(punctuator)', snippet);
}
}
}
}
};
}());
function define(kind, token) {
// Define a name.
var name = token.string,
master = scope[name]; // The current definition of the name
// vars are created with a deadzone, so that the expression that initializes
// the var cannot access the var. Functions are not writeable.
token.dead = false;
token.init = false;
token.kind = kind;
token.master = master;
token.used = 0;
token.writeable = true;
// Global variables are a little weird. They can be defined multiple times.
// Some predefined global vars are (or should) not be writeable.
if (kind === 'var' && funct === global_funct) {
if (!master) {
if (predefined[name] === false) {
token.writeable = false;
}
global_scope[name] = token;
}
} else {
// It is an error if the name has already been defined in this scope, except
// when reusing an exception variable name.
if (master) {
if (master.function === funct) {
if (master.kind !== 'exception' || kind !== 'exception' ||
!master.dead) {
token.warn('already_defined', name);
}
} else if (master.function !== global_funct) {
if (kind === 'var') {
token.warn('redefinition_a_b', name, master.line);
}
}
}
scope[name] = token;
if (kind === 'var') {
block_var.push(name);
}
}
}
function peek(distance) {
// Peek ahead to a future token. The distance is how far ahead to look. The
// default is the next token.
var found, slot = 0;
distance = distance || 0;
while (slot <= distance) {
found = lookahead[slot];
if (!found) {
found = lookahead[slot] = lex.token();
}
slot += 1;
}
return found;
}
function advance(id, match) {
// Produce the next token, also looking for programming errors.
if (indent) {
// If indentation checking was requested, then inspect all of the line breakings.
// The var statement is tricky because the names might be aligned or not. We
// look at the first line break after the var to determine the programmer's
// intention.
if (var_mode && next_token.line !== token.line) {
if ((var_mode !== indent || !next_token.edge) &&
next_token.from === indent.at -
(next_token.edge ? option.indent : 0)) {
var dent = indent;
for (;;) {
dent.at -= option.indent;
if (dent === var_mode) {
break;
}
dent = dent.was;
}
dent.open = false;
}
var_mode = null;
}
if (next_token.id === '?' && indent.mode === ':' &&
token.line !== next_token.line) {
indent.at -= option.indent;
}
if (indent.open) {
// If the token is an edge.
if (next_token.edge) {
if (next_token.edge === 'label') {
expected_at(1);
} else if (next_token.edge === 'case' || indent.mode === 'statement') {
expected_at(indent.at - option.indent);
} else if (indent.mode !== 'array' || next_token.line !== token.line) {
expected_at(indent.at);
}
// If the token is not an edge, but is the first token on the line.
} else if (next_token.line !== token.line) {
if (next_token.from < indent.at + (indent.mode ===
'expression' ? 0 : option.indent)) {
expected_at(indent.at + option.indent);
}
indent.wrap = true;
}
} else if (next_token.line !== token.line) {
if (next_token.edge) {
expected_at(indent.at);
} else {
indent.wrap = true;
if (indent.mode === 'statement' || indent.mode === 'var') {
expected_at(indent.at + option.indent);
} else if (next_token.from < indent.at + (indent.mode ===
'expression' ? 0 : option.indent)) {
expected_at(indent.at + option.indent);
}
}
}
}
switch (token.id) {
case '(number)':
if (next_token.id === '.') {
next_token.warn('trailing_decimal_a');
}
break;
case '-':
if (next_token.id === '-' || next_token.id === '--') {
next_token.warn('confusing_a');
}
break;
case '+':
if (next_token.id === '+' || next_token.id === '++') {
next_token.warn('confusing_a');
}
break;
}
if (token.id === '(string)' || token.identifier) {
anonname = token.string;
}
if (id && next_token.id !== id) {
if (match) {
next_token.warn('expected_a_b_from_c_d', id,
match.id, match.line, artifact());
} else if (!next_token.identifier || next_token.string !== id) {
next_token.warn('expected_a_b', id, artifact());
}
}
prev_token = token;
token = next_token;
next_token = lookahead.shift() || lex.token();
next_token.function = funct;
tokens.push(next_token);
}
function do_globals() {
var name, writeable;
for (;;) {
if (next_token.id !== '(string)' && !next_token.identifier) {
return;
}
name = next_token.string;
advance();
writeable = false;
if (next_token.id === ':') {
advance(':');
switch (next_token.id) {
case 'true':
writeable = predefined[name] !== false;
advance('true');
break;
case 'false':
advance('false');
break;
default:
next_token.stop('unexpected_a');
}
}
predefined[name] = writeable;
if (next_token.id !== ',') {
return;
}
advance(',');
}
}
function do_jslint() {
var name, value;
while (next_token.id === '(string)' || next_token.identifier) {
name = next_token.string;
if (!allowed_option[name]) {
next_token.stop('unexpected_a');
}
advance();
if (next_token.id !== ':') {
next_token.stop('expected_a_b', ':', artifact());
}
advance(':');
if (typeof allowed_option[name] === 'number') {
value = next_token.number;
if (value > allowed_option[name] || value <= 0 ||
Math.floor(value) !== value) {
next_token.stop('expected_small_a');
}
option[name] = value;
} else {
if (next_token.id === 'true') {
option[name] = true;
} else if (next_token.id === 'false') {
option[name] = false;
} else {
next_token.stop('unexpected_a');
}
}
advance();
if (next_token.id === ',') {
advance(',');
}
}
assume();
}
function do_properties() {
var name;
option.properties = true;
for (;;) {
if (next_token.id !== '(string)' && !next_token.identifier) {
return;
}
name = next_token.string;
advance();
if (next_token.id === ':') {
for (;;) {
advance();
if (next_token.id !== '(string)' && !next_token.identifier) {
break;
}
}
}
property[name] = 0;
if (next_token.id !== ',') {
return;
}
advance(',');
}
}
directive = function directive() {
var command = this.id,
old_comments_off = comments_off,
old_indent = indent;
comments_off = true;
indent = null;
if (next_token.line === token.line && next_token.from === token.thru) {
next_token.warn('missing_space_a_b', artifact(token), artifact());
}
if (lookahead.length > 0) {
this.warn('unexpected_a');
}
switch (command) {
case '/*properties':
case '/*property':
case '/*members':
case '/*member':
do_properties();
break;
case '/*jslint':
do_jslint();
break;
case '/*globals':
case '/*global':
do_globals();
break;
default:
this.stop('unexpected_a');
}
comments_off = old_comments_off;
advance('*/');
indent = old_indent;
};
// Indentation intention
function edge(mode) {
next_token.edge = indent ? indent.open && (mode || 'edge') : '';
}
function step_in(mode) {
var open;
if (typeof mode === 'number') {
indent = {
at: +mode,
open: true,
was: indent
};
} else if (!indent) {
indent = {
at: 1,
mode: 'statement',
open: true
};
} else if (mode === 'statement') {
indent = {
at: indent.at,
open: true,
was: indent
};
} else {
open = mode === 'var' || next_token.line !== token.line;
indent = {
at: (open || mode === 'control'
? indent.at + option.indent
: indent.at) + (indent.wrap ? option.indent : 0),
mode: mode,
open: open,
was: indent
};
if (mode === 'var' && open) {
var_mode = indent;
}
}
}
function step_out(id, symbol) {
if (id) {
if (indent && indent.open) {
indent.at -= option.indent;
edge();
}
advance(id, symbol);
}
if (indent) {
indent = indent.was;
}
}
// Functions for conformance of whitespace.
function one_space(left, right) {
left = left || token;
right = right || next_token;
if (right.id !== '(end)' && !option.white &&
(token.line !== right.line ||
token.thru + 1 !== right.from)) {
right.warn('expected_space_a_b', artifact(token), artifact(right));
}
}
function one_space_only(left, right) {
left = left || token;
right = right || next_token;
if (right.id !== '(end)' && (left.line !== right.line ||
(!option.white && left.thru + 1 !== right.from))) {
right.warn('expected_space_a_b', artifact(left), artifact(right));
}
}
function no_space(left, right) {
left = left || token;
right = right || next_token;
if ((!option.white) &&
left.thru !== right.from && left.line === right.line) {
right.warn('unexpected_space_a_b', artifact(left), artifact(right));
}
}
function no_space_only(left, right) {
left = left || token;
right = right || next_token;
if (right.id !== '(end)' && (left.line !== right.line ||
(!option.white && left.thru !== right.from))) {
right.warn('unexpected_space_a_b', artifact(left), artifact(right));
}
}
function spaces(left, right) {
if (!option.white) {
left = left || token;
right = right || next_token;
if (left.thru === right.from && left.line === right.line) {
right.warn('missing_space_a_b', artifact(left), artifact(right));
}
}
}
function comma() {
if (next_token.id !== ',') {
warn('expected_a_b', token.line, token.thru, ',', artifact());
} else {
if (!option.white) {
no_space_only();
}
advance(',');
spaces();
}
}
function semicolon() {
if (next_token.id !== ';') {
warn('expected_a_b', token.line, token.thru, ';', artifact());
} else {
if (!option.white) {
no_space_only();
}
advance(';');
if (semicolon_coda[next_token.id] !== true) {
spaces();
}
}
}
function use_strict() {
if (next_token.string === 'use strict') {
if (strict_mode) {
next_token.warn('unnecessary_use');
}
edge();
advance();
semicolon();
strict_mode = true;
return true;
}
return false;
}
function are_similar(a, b) {
if (a === b) {
return true;
}
if (Array.isArray(a)) {
if (Array.isArray(b) && a.length === b.length) {
var i;
for (i = 0; i < a.length; i += 1) {
if (!are_similar(a[i], b[i])) {
return false;
}
}
return true;
}
return false;
}
if (Array.isArray(b)) {
return false;
}
if (a.id === '(number)' && b.id === '(number)') {
return a.number === b.number;
}
if (a.arity === b.arity && a.string === b.string) {
switch (a.arity) {
case undefined:
return a.string === b.string;
case 'prefix':
case 'suffix':
return a.id === b.id && are_similar(a.first, b.first) &&
a.id !== '{' && a.id !== '[';
case 'infix':
return are_similar(a.first, b.first) &&
are_similar(a.second, b.second);
case 'ternary':
return are_similar(a.first, b.first) &&
are_similar(a.second, b.second) &&
are_similar(a.third, b.third);
case 'function':
case 'regexp':
return false;
default:
return true;
}
}
if (a.id === '.' && b.id === '[' && b.arity === 'infix') {
return a.second.string === b.second.string && b.second.id === '(string)';
}
if (a.id === '[' && a.arity === 'infix' && b.id === '.') {
return a.second.string === b.second.string && a.second.id === '(string)';
}
return false;
}
// This is the heart of JSLINT, the Pratt parser. In addition to parsing, it
// is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is
// like .nud except that it is only used on the first token of a statement.
// Having .fud makes it much easier to define statement-oriented languages like
// JavaScript. I retained Pratt's nomenclature.
// .nud Null denotation
// .fud First null denotation
// .led Left denotation
// lbp Left binding power
// rbp Right binding power
// They are elements of the parsing method called Top Down Operator Precedence.
function expression(rbp, initial) {
// rbp is the right binding power.
// initial indicates that this is the first expression of a statement.
var left;
if (next_token.id === '(end)') {
token.stop('unexpected_a', next_token.id);
}
advance();
if (initial) {
anonname = 'anonymous';
}
if (initial === true && token.fud) {
left = token.fud();
} else {
if (token.nud) {
left = token.nud();
} else {
if (next_token.id === '(number)' && token.id === '.') {
token.warn('leading_decimal_a', artifact());
advance();
return token;
}
token.stop('expected_identifier_a', artifact(token));
}
while (rbp < next_token.lbp) {
advance();
left = token.led(left);
}
}
if (left && left.assign && !initial) {
if (!option.ass) {
left.warn('assignment_expression');
}
if (left.id !== '=' && left.first.master) {
left.first.master.used = true;
}
}
return left;
}
protosymbol = {
nud: function () {
this.stop('unexpected_a');
},
led: function () {
this.stop('expected_operator_a');
},
warn: function (code, a, b, c, d) {
if (!this.warning) {
this.warning = warn(code, this.line || 0, this.from || 0,
a || artifact(this), b, c, d);
}
},
stop: function (code, a, b, c, d) {
this.warning = undefined;
this.warn(code, a, b, c, d);
return quit('stopping', this.line, this.character);
},
lbp: 0
};
// Functional constructors for making the symbols that will be inherited by
// tokens.
function symbol(s, bp) {
var x = syntax[s];
if (!x) {
x = Object.create(protosymbol);
x.id = x.string = s;
x.lbp = bp || 0;
syntax[s] = x;
}
return x;
}
function postscript(x) {
x.postscript = true;
return x;
}
function ultimate(s) {
var x = symbol(s, 0);
x.from = 1;
x.thru = 1;
x.line = 0;
x.edge = 'edge';
x.string = s;
return postscript(x);
}
function reserve_name(x) {
var c = x.id.charAt(0);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
x.identifier = x.reserved = true;
}
return x;
}
function stmt(s, f) {
var x = symbol(s);
x.fud = f;
return reserve_name(x);
}
function disrupt_stmt(s, f) {
var x = stmt(s, f);
x.disrupt = true;
}
function labeled_stmt(s, f) {
var x = stmt(s, function labeled() {
var the_statement;
if (funct.breakage) {
funct.breakage.push(this);
} else {
funct.breakage = [this];
}
the_statement = f.apply(this);
if (funct.breakage.length > 1) {
funct.breakage.pop();
} else {
delete funct.breakage;
}
return the_statement;
});
x.labeled = true;
}
function prefix(s, f) {
var x = symbol(s, 150);
reserve_name(x);
x.nud = function () {
var that = this;
that.arity = 'prefix';
if (typeof f === 'function') {
that = f(that);
if (that.arity !== 'prefix') {
return that;
}
} else {
if (s === 'typeof') {
one_space();
} else {
no_space_only();
}
that.first = expression(150);
}
switch (that.id) {
case '++':
case '--':
if (!option.plusplus) {
that.warn('unexpected_a');
} else if ((!that.first.identifier || that.first.reserved) &&
that.first.id !== '.' && that.first.id !== '[') {
that.warn('bad_operand');
}
break;
default:
if (that.first.arity === 'prefix' ||
that.first.arity === 'function') {
that.warn('unexpected_a');
}
}
return that;
};
return x;
}
function type(s, t, nud) {
var x = symbol(s);
x.arity = t;
if (nud) {
x.nud = nud;
}
return x;
}
function reserve(s, f) {
var x = symbol(s);
x.identifier = x.reserved = true;
if (typeof f === 'function') {
x.nud = f;
}
return x;
}
function constant(name) {
var x = reserve(name);
x.string = name;
x.nud = return_this;
return x;
}
function reservevar(s, v) {
return reserve(s, function () {
if (typeof v === 'function') {
v(this);
}
return this;
});
}
function infix(s, p, f, w) {
var x = symbol(s, p);
reserve_name(x);
x.led = function (left) {
this.arity = 'infix';
if (!w) {
spaces(prev_token, token);
spaces();
}
if (!option.bitwise && this.bitwise) {
this.warn('unexpected_a');
}
if (typeof f === 'function') {
return f(left, this);
}
this.first = left;
this.second = expression(p);
return this;
};
return x;
}
function expected_relation(node, message) {
if (node.assign) {
node.warn(message || 'conditional_assignment');
}
return node;
}
function expected_condition(node, message) {
switch (node.id) {
case '[':
case '-':
if (node.arity !== 'infix') {
node.warn(message || 'weird_condition');
}
break;
case 'false':
case 'function':
case 'Infinity':
case 'NaN':
case 'null':
case 'true':
case 'undefined':
case 'void':
case '(number)':
case '(regexp)':
case '(string)':
case '{':
case '?':
case '~':
node.warn(message || 'weird_condition');
break;
case '(':
if (node.first.id === 'new' ||
(node.first.string === 'Boolean') ||
(node.first.id === '.' &&
numbery[node.first.second.string] === true)) {
node.warn(message || 'weird_condition');
}
break;
}
return node;
}
function check_relation(node) {
switch (node.arity) {
case 'prefix':
switch (node.id) {
case '{':
case '[':
node.warn('unexpected_a');
break;
case '!':
node.warn('confusing_a');
break;
}
break;
case 'function':
case 'regexp':
node.warn('unexpected_a');
break;
default:
if (node.id === 'NaN') {
node.warn('isNaN');
} else if (node.relation) {
node.warn('weird_relation');
}
}
return node;
}
function relation(s, eqeq) {
var x = infix(s, 100, function (left, that) {
check_relation(left);
if (eqeq && !option.eqeq) {
that.warn('expected_a_b', eqeq, that.id);
}
var right = expression(100);
if (are_similar(left, right) ||
((left.id === '(string)' || left.id === '(number)') &&
(right.id === '(string)' || right.id === '(number)'))) {
that.warn('weird_relation');
} else if (left.id === 'typeof') {
if (right.id !== '(string)') {
right.warn("expected_string_a", artifact(right));
} else if (right.string === 'undefined' ||
right.string === 'null') {
left.warn("unexpected_typeof_a", right.string);
}
} else if (right.id === 'typeof') {
if (left.id !== '(string)') {
left.warn("expected_string_a", artifact(left));
} else if (left.string === 'undefined' ||
left.string === 'null') {
right.warn("unexpected_typeof_a", left.string);
}
}
that.first = left;
that.second = check_relation(right);
return that;
});
x.relation = true;
return x;
}
function lvalue(that, s) {
var master;
if (that.identifier) {
master = scope[that.string];
if (master) {
if (scope[that.string].writeable !== true) {
that.warn('read_only');
}
master.used -= 1;
if (s === '=') {
master.init = true;
}
}
} else if (that.id === '.' || that.id === '[') {
if (!that.first || that.first.string === 'arguments') {
that.warn('bad_assignment');
}
} else {
that.warn('bad_assignment');
}
}
function assignop(s, op) {
var x = infix(s, 20, function (left, that) {
var next;
that.first = left;
lvalue(left, s);
that.second = expression(20);
if (that.id === '=' && are_similar(that.first, that.second)) {
that.warn('weird_assignment');
}
next = that;
while (next_token.id === '=') {
lvalue(next.second, '=');
next_token.first = next.second;
next.second = next_token;
next = next_token;
advance('=');
next.second = expression(20);
}
return that;
});
x.assign = true;
if (op) {
if (syntax[op].bitwise) {
x.bitwise = true;
}
}
return x;
}
function bitwise(s, p) {
var x = infix(s, p, 'number');
x.bitwise = true;
return x;
}
function suffix(s) {
var x = symbol(s, 150);
x.led = function (left) {
no_space_only(prev_token, token);
if (!option.plusplus) {
this.warn('unexpected_a');
} else if ((!left.identifier || left.reserved) &&
left.id !== '.' && left.id !== '[') {
this.warn('bad_operand');
}
this.first = left;
this.arity = 'suffix';
return this;
};
return x;
}
function optional_identifier(variable) {
if (next_token.identifier) {
advance();
if (token.reserved && variable) {
token.warn('expected_identifier_a_reserved');
}
return token.string;
}
}
function identifier(variable) {
var i = optional_identifier(variable);
if (!i) {
next_token.stop(token.id === 'function' && next_token.id === '('
? 'name_function'
: 'expected_identifier_a');
}
return i;
}
function statement() {
var label, preamble, the_statement;
// We don't like the empty statement.
if (next_token.id === ';') {
next_token.warn('unexpected_a');
semicolon();
return;
}
// Is this a labeled statement?
if (next_token.identifier && !next_token.reserved && peek().id === ':') {
edge('label');
label = next_token;
advance();
advance(':');
define('label', label);
if (next_token.labeled !== true || funct === global_funct) {
label.stop('unexpected_label_a');
} else if (jx.test(label.string + ':')) {
label.warn('url');
}
next_token.label = label;
label.init = true;
label.statement = next_token;
}
// Parse the statement.
preamble = next_token;
if (token.id !== 'else') {
edge();
}
step_in('statement');
the_statement = expression(0, true);
if (the_statement) {
// Look for the final semicolon.
if (the_statement.arity === 'statement') {
if (the_statement.id === 'switch' ||
(the_statement.block && the_statement.id !== 'do')) {
spaces();
} else {
semicolon();
}
} else {
// If this is an expression statement, determine if it is acceptable.
// We do not like
// new Blah;
// statements. If it is to be used at all, new should only be used to make
// objects, not side effects. The expression statements we do like do
// assignment or invocation or delete.
if (the_statement.id === '(') {
if (the_statement.first.id === 'new') {
next_token.warn('bad_new');
}
} else if (the_statement.id === '++' ||
the_statement.id === '--') {
lvalue(the_statement.first);
} else if (!the_statement.assign &&
the_statement.id !== 'delete') {
if (!option.closure || !preamble.comments) {
preamble.warn('assignment_function_expression');
}
}
semicolon();
}
}
step_out();
if (label) {
label.dead = true;
}
return the_statement;
}
function statements() {
var array = [], disruptor, the_statement;
// A disrupt statement may not be followed by any other statement.
// If the last statement is disrupt, then the sequence is disrupt.
while (next_token.postscript !== true) {
if (next_token.id === ';') {
next_token.warn('unexpected_a');
semicolon();
} else {
if (next_token.string === 'use strict') {
if ((!node_js) || funct !== global_funct || array.length > 0) {
next_token.warn('function_strict');
}
use_strict();
}
if (disruptor) {
next_token.warn('unreachable_a_b', next_token.string,
disruptor.string);
disruptor = null;
}
the_statement = statement();
if (the_statement) {
array.push(the_statement);
if (the_statement.disrupt) {
disruptor = the_statement;
array.disrupt = true;
}
}
}
}
return array;
}
function block(kind) {
// A block is a sequence of statements wrapped in braces.
var array,
curly = next_token,
old_block_var = block_var,
old_in_block = in_block,
old_strict_mode = strict_mode;
in_block = kind !== 'function' && kind !== 'try' && kind !== 'catch';
block_var = [];
if (curly.id === '{') {
spaces();
advance('{');
step_in();
if (kind === 'function' && !use_strict() && !old_strict_mode &&
!option.sloppy && funct.level === 1) {
next_token.warn('missing_use_strict');
}
array = statements();
strict_mode = old_strict_mode;
step_out('}', curly);
} else if (in_block) {
curly.stop('expected_a_b', '{', artifact());
} else {
curly.warn('expected_a_b', '{', artifact());
array = [statement()];
array.disrupt = array[0].disrupt;
}
if (kind !== 'catch' && array.length === 0 && !option.debug) {
curly.warn('empty_block');
}
block_var.forEach(function (name) {
scope[name].dead = true;
});
block_var = old_block_var;
in_block = old_in_block;
return array;
}
function tally_property(name) {
if (option.properties && typeof property[name] !== 'number') {
token.warn('unexpected_property_a', name);
}
if (property[name]) {
property[name] += 1;
} else {
property[name] = 1;
}
}
// ECMAScript parser
(function () {
var x = symbol('(identifier)');
x.nud = function () {
var name = this.string,
master = scope[name],
writeable;
// If the master is not in scope, then we may have an undeclared variable.
// Check the predefined list. If it was predefined, create the global
// variable.
if (!master) {
writeable = predefined[name];
if (typeof writeable === 'boolean') {
global_scope[name] = master = {
dead: false,
function: global_funct,
kind: 'var',
string: name,
writeable: writeable
};
// But if the variable is not in scope, and is not predefined, and if we are not
// in the global scope, then we have an undefined variable error.
} else {
token.warn('used_before_a');
}
} else {
this.master = master;
}
// Annotate uses that cross scope boundaries.
if (master) {
if (master.kind === 'label') {
this.warn('a_label');
} else {
if (master.dead === true || master.dead === funct) {
this.warn('a_scope');
}
master.used += 1;
if (master.function !== funct) {
if (master.function === global_funct) {
funct.global.push(name);
} else {
master.function.closure.push(name);
funct.outer.push(name);
}
}
}
}
return this;
};
x.identifier = true;
}());
// Build the syntax table by declaring the syntactic elements.
type('(array)', 'array');
type('(function)', 'function');
type('(number)', 'number', return_this);
type('(object)', 'object');
type('(string)', 'string', return_this);
type('(boolean)', 'boolean', return_this);
type('(regexp)', 'regexp', return_this);
ultimate('(begin)');
ultimate('(end)');
ultimate('(error)');
postscript(symbol('}'));
symbol(')');
symbol(']');
postscript(symbol('"'));
postscript(symbol('\''));
symbol(';');
symbol(':');
symbol(',');
symbol('#');
symbol('@');
symbol('*/');
postscript(reserve('case'));
reserve('catch');
postscript(reserve('default'));
reserve('else');
reserve('finally');
reservevar('arguments', function (x) {
if (strict_mode && funct === global_funct) {
x.warn('strict');
}
funct.arguments = true;
});
reservevar('eval');
constant('false', 'boolean');
constant('Infinity', 'number');
constant('NaN', 'number');
constant('null', '');
reservevar('this', function (x) {
if (strict_mode && funct.statement && funct.name.charAt(0) > 'Z') {
x.warn('strict');
}
});
constant('true', 'boolean');
constant('undefined', '');
infix('?', 30, function (left, that) {
step_in('?');
that.first = expected_condition(expected_relation(left));
that.second = expression(0);
spaces();
step_out();
var colon = next_token;
advance(':');
step_in(':');
spaces();
that.third = expression(10);
that.arity = 'ternary';
if (are_similar(that.second, that.third)) {
colon.warn('weird_ternary');
} else if (are_similar(that.first, that.second)) {
that.warn('use_or');
}
step_out();
return that;
});
infix('||', 40, function (left, that) {
function paren_check(that) {
if (that.id === '&&' && !that.paren) {
that.warn('and');
}
return that;
}
that.first = paren_check(expected_condition(expected_relation(left)));
that.second = paren_check(expected_relation(expression(40)));
if (are_similar(that.first, that.second)) {
that.warn('weird_condition');
}
return that;
});
infix('&&', 50, function (left, that) {
that.first = expected_condition(expected_relation(left));
that.second = expected_relation(expression(50));
if (are_similar(that.first, that.second)) {
that.warn('weird_condition');
}
return that;
});
prefix('void', function (that) {
that.first = expression(0);
that.warn('expected_a_b', 'undefined', 'void');
return that;
});
bitwise('|', 70);
bitwise('^', 80);
bitwise('&', 90);
relation('==', '===');
relation('===');
relation('!=', '!==');
relation('!==');
relation('<');
relation('>');
relation('<=');
relation('>=');
bitwise('<<', 120);
bitwise('>>', 120);
bitwise('>>>', 120);
infix('in', 120, function (left, that) {
that.warn('infix_in');
that.left = left;
that.right = expression(130);
return that;
});
infix('instanceof', 120);
infix('+', 130, function (left, that) {
if (left.id === '(number)') {
if (left.number === 0) {
left.warn('unexpected_a', '0');
}
} else if (left.id === '(string)') {
if (left.string === '') {
left.warn('expected_a_b', 'String', '\'\'');
}
}
var right = expression(130);
if (right.id === '(number)') {
if (right.number === 0) {
right.warn('unexpected_a', '0');
}
} else if (right.id === '(string)') {
if (right.string === '') {
right.warn('expected_a_b', 'String', '\'\'');
}
}
if (left.id === right.id) {
if (left.id === '(string)' || left.id === '(number)') {
if (left.id === '(string)') {
left.string += right.string;
if (jx.test(left.string)) {
left.warn('url');
}
} else {
left.number += right.number;
}
left.thru = right.thru;
return left;
}
}
that.first = left;
that.second = right;
return that;
});
prefix('+');
prefix('+++', function () {
token.warn('confusing_a');
this.first = expression(150);
this.arity = 'prefix';
return this;
});
infix('+++', 130, function (left) {
token.warn('confusing_a');
this.first = left;
this.second = expression(130);
return this;
});
infix('-', 130, function (left, that) {
if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') {
left.warn('unexpected_a');
}
var right = expression(130);
if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') {
right.warn('unexpected_a');
}
if (left.id === right.id && left.id === '(number)') {
left.number -= right.number;
left.thru = right.thru;
return left;
}
that.first = left;
that.second = right;
return that;
});
prefix('-');
prefix('---', function () {
token.warn('confusing_a');
this.first = expression(150);
this.arity = 'prefix';
return this;
});
infix('---', 130, function (left) {
token.warn('confusing_a');
this.first = left;
this.second = expression(130);
return this;
});
infix('*', 140, function (left, that) {
if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') {
left.warn('unexpected_a');
}
var right = expression(140);
if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') {
right.warn('unexpected_a');
}
if (left.id === right.id && left.id === '(number)') {
left.number *= right.number;
left.thru = right.thru;
return left;
}
that.first = left;
that.second = right;
return that;
});
infix('/', 140, function (left, that) {
if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') {
left.warn('unexpected_a');
}
var right = expression(140);
if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') {
right.warn('unexpected_a');
}
if (left.id === right.id && left.id === '(number)') {
left.number /= right.number;
left.thru = right.thru;
return left;
}
that.first = left;
that.second = right;
return that;
});
infix('%', 140, function (left, that) {
if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') {
left.warn('unexpected_a');
}
var right = expression(140);
if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') {
right.warn('unexpected_a');
}
if (left.id === right.id && left.id === '(number)') {
left.number %= right.number;
left.thru = right.thru;
return left;
}
that.first = left;
that.second = right;
return that;
});
suffix('++');
prefix('++');
suffix('--');
prefix('--');
prefix('delete', function (that) {
one_space();
var p = expression(0);
if (!p || (p.id !== '.' && p.id !== '[')) {
next_token.warn('deleted');
}
that.first = p;
return that;
});
prefix('~', function (that) {
no_space_only();
if (!option.bitwise) {
that.warn('unexpected_a');
}
that.first = expression(150);
return that;
});
function banger(that) {
no_space_only();
that.first = expected_condition(expression(150));
if (bang[that.first.id] === that || that.first.assign) {
that.warn('confusing_a');
}
return that;
}
prefix('!', banger);
prefix('!!', banger);
prefix('typeof');
prefix('new', function (that) {
one_space();
var c = expression(160), n, p, v;
that.first = c;
if (c.id !== 'function') {
if (c.identifier) {
switch (c.string) {
case 'Object':
token.warn('use_object');
break;
case 'Array':
if (next_token.id === '(') {
p = next_token;
p.first = this;
advance('(');
if (next_token.id !== ')') {
n = expression(0);
p.second = [n];
if (n.id === '(string)' || next_token.id === ',') {
p.warn('use_array');
}
while (next_token.id === ',') {
advance(',');
p.second.push(expression(0));
}
} else {
token.warn('use_array');
}
advance(')', p);
return p;
}
token.warn('use_array');
break;
case 'Number':
case 'String':
case 'Boolean':
case 'Math':
case 'JSON':
c.warn('not_a_constructor');
break;
case 'Function':
if (!option.evil) {
next_token.warn('function_eval');
}
break;
case 'Date':
case 'RegExp':
case 'this':
break;
default:
if (c.id !== 'function') {
v = c.string.charAt(0);
if (!option.newcap && (v < 'A' || v > 'Z')) {
token.warn('constructor_name_a');
}
}
}
} else {
if (c.id !== '.' && c.id !== '[' && c.id !== '(') {
token.warn('bad_constructor');
}
}
} else {
that.warn('weird_new');
}
if (next_token.id !== '(') {
next_token.warn('missing_a', '()');
}
return that;
});
infix('(', 160, function (left, that) {
var e, p;
if (indent && indent.mode === 'expression') {
no_space(prev_token, token);
} else {
no_space_only(prev_token, token);
}
if (!left.immed && left.id === 'function') {
next_token.warn('wrap_immediate');
}
p = [];
if (left.identifier) {
if (left.string.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) {
if (left.string !== 'Number' && left.string !== 'String' &&
left.string !== 'Boolean' && left.string !== 'Date') {
if (left.string === 'Math') {
left.warn('not_a_function');
} else if (left.string === 'Object') {
token.warn('use_object');
} else if (left.string === 'Array' || !option.newcap) {
left.warn('missing_a', 'new');
}
}
} else if (left.string === 'JSON') {
left.warn('not_a_function');
}
} else if (left.id === '.') {
if (left.second.string === 'split' &&
left.first.id === '(string)') {
left.second.warn('use_array');
}
}
step_in();
if (next_token.id !== ')') {
no_space();
for (;;) {
edge();
e = expression(10);
if (left.string === 'Boolean' && (e.id === '!' || e.id === '~')) {
e.warn('weird_condition');
}
p.push(e);
if (next_token.id !== ',') {
break;
}
comma();
}
}
no_space();
step_out(')', that);
if (typeof left === 'object') {
if (left.string === 'parseInt' && p.length === 1) {
left.warn('radix');
} else if (left.string === 'String' && p.length >= 1 && p[0].id === '(string)') {
left.warn('unexpected_a');
}
if (!option.evil) {
if (left.string === 'eval' || left.string === 'Function' ||
left.string === 'execScript') {
left.warn('evil');
} else if (p[0] && p[0].id === '(string)' &&
(left.string === 'setTimeout' ||
left.string === 'setInterval')) {
left.warn('implied_evil');
}
}
if (!left.identifier && left.id !== '.' && left.id !== '[' &&
left.id !== '(' && left.id !== '&&' && left.id !== '||' &&
left.id !== '?') {
left.warn('bad_invocation');
}
if (left.id === '.') {
if (p.length > 0 &&
left.first && left.first.first &&
are_similar(p[0], left.first.first)) {
if (left.second.string === 'call' ||
(left.second.string === 'apply' && (p.length === 1 ||
(p[1].arity === 'prefix' && p[1].id === '[')))) {
left.second.warn('unexpected_a');
}
}
if (left.second.string === 'toString') {
if (left.first.id === '(string)' || left.first.id === '(number)') {
left.second.warn('unexpected_a');
}
}
}
}
that.first = left;
that.second = p;
return that;
}, true);
prefix('(', function (that) {
step_in('expression');
no_space();
edge();
if (next_token.id === 'function') {
next_token.immed = true;
}
var value = expression(0);
value.paren = true;
no_space();
step_out(')', that);
if (value.id === 'function') {
switch (next_token.id) {
case '(':
next_token.warn('move_invocation');
break;
case '.':
case '[':
next_token.warn('unexpected_a');
break;
default:
that.warn('bad_wrap');
}
} else if (!value.arity) {
if (!option.closure || !that.comments) {
that.warn('unexpected_a');
}
}
return value;
});
infix('.', 170, function (left, that) {
no_space(prev_token, token);
no_space();
var name = identifier();
if (typeof name === 'string') {
tally_property(name);
}
that.first = left;
that.second = token;
if (left && left.string === 'arguments' &&
(name === 'callee' || name === 'caller')) {
left.warn('avoid_a', 'arguments.' + name);
} else if (!option.evil && left && left.string === 'document' &&
(name === 'write' || name === 'writeln')) {
left.warn('write_is_wrong');
} else if (!option.stupid && syx.test(name)) {
token.warn('sync_a');
}
if (!option.evil && (name === 'eval' || name === 'execScript')) {
next_token.warn('evil');
}
return that;
}, true);
infix('[', 170, function (left, that) {
var e, s;
no_space_only(prev_token, token);
no_space();
step_in();
edge();
e = expression(0);
switch (e.id) {
case '(number)':
if (e.id === '(number)' && left.id === 'arguments') {
left.warn('use_param');
}
break;
case '(string)':
if (!option.evil &&
(e.string === 'eval' || e.string === 'execScript')) {
e.warn('evil');
} else if (!option.sub && ix.test(e.string)) {
s = syntax[e.string];
if (!s || !s.reserved) {
e.warn('subscript');
}
}
tally_property(e.string);
break;
}
step_out(']', that);
no_space(prev_token, token);
that.first = left;
that.second = e;
return that;
}, true);
prefix('[', function (that) {
that.first = [];
step_in('array');
while (next_token.id !== '(end)') {
while (next_token.id === ',') {
next_token.warn('unexpected_a');
advance(',');
}
if (next_token.id === ']') {
break;
}
indent.wrap = false;
edge();
that.first.push(expression(10));
if (next_token.id === ',') {
comma();
if (next_token.id === ']') {
token.warn('unexpected_a');
break;
}
} else {
break;
}
}
step_out(']', that);
return that;
}, 170);
function property_name() {
var id = optional_identifier();
if (!id) {
if (next_token.id === '(string)') {
id = next_token.string;
advance();
} else if (next_token.id === '(number)') {
id = next_token.number.toString();
advance();
}
}
return id;
}
assignop('=');
assignop('+=', '+');
assignop('-=', '-');
assignop('*=', '*');
assignop('/=', '/').nud = function () {
next_token.stop('slash_equal');
};
assignop('%=', '%');
assignop('&=', '&');
assignop('|=', '|');
assignop('^=', '^');
assignop('<<=', '<<');
assignop('>>=', '>>');
assignop('>>>=', '>>>');
function function_parameters() {
var id, parameters = [], paren = next_token;
advance('(');
token.function = funct;
step_in();
no_space();
if (next_token.id !== ')') {
for (;;) {
edge();
id = identifier();
define('parameter', token);
parameters.push(id);
token.init = true;
token.writeable = true;
if (next_token.id !== ',') {
break;
}
comma();
}
}
no_space();
step_out(')', paren);
return parameters;
}
function do_function(func, name) {
var old_funct = funct,
old_option = option,
old_scope = scope;
scope = Object.create(old_scope);
funct = {
closure: [],
global: [],
level: old_funct.level + 1,
line: next_token.line,
loopage: 0,
name: name || '\'' + (anonname || '').replace(nx, sanitize) + '\'',
outer: [],
scope: scope
};
funct.parameter = function_parameters();
func.function = funct;
option = Object.create(old_option);
functions.push(funct);
if (name) {
func.name = name;
func.string = name;
define('function', func);
func.init = true;
func.used += 1;
}
func.writeable = false;
one_space();
func.block = block('function');
Object.keys(scope).forEach(function (name) {
var master = scope[name];
if (!master.used && master.kind !== 'exception' &&
(master.kind !== 'parameter' || !option.unparam)) {
master.warn('unused_a');
} else if (!master.init) {
master.warn('uninitialized_a');
}
});
funct = old_funct;
option = old_option;
scope = old_scope;
}
prefix('{', function (that) {
var get, i, j, name, set, seen = Object.create(null);
that.first = [];
step_in();
while (next_token.id !== '}') {
indent.wrap = false;
// JSLint recognizes the ES5 extension for get/set in object literals,
// but requires that they be used in pairs.
edge();
if (next_token.string === 'get' && peek().id !== ':') {
get = next_token;
advance('get');
one_space_only();
name = next_token;
i = property_name();
if (!i) {
next_token.stop('missing_property');
}
get.string = '';
do_function(get);
if (funct.loopage) {
get.warn('function_loop');
}
if (get.function.parameter.length) {
get.warn('parameter_a_get_b', get.function.parameter[0], i);
}
comma();
set = next_token;
spaces();
edge();
advance('set');
set.string = '';
one_space_only();
j = property_name();
if (i !== j) {
token.stop('expected_a_b', i, j || next_token.string);
}
do_function(set);
if (set.block.length === 0) {
token.warn('missing_a', 'throw');
}
if (set.function.parameter.length === 0) {
set.stop('parameter_set_a', 'value');
} else if (set.function.parameter[0] !== 'value') {
set.stop('expected_a_b', 'value',
set.function.parameter[0]);
}
name.first = [get, set];
} else {
name = next_token;
i = property_name();
if (typeof i !== 'string') {
next_token.stop('missing_property');
}
advance(':');
spaces();
name.first = expression(10);
}
that.first.push(name);
if (seen[i] === true) {
next_token.warn('duplicate_a', i);
}
seen[i] = true;
tally_property(i);
if (next_token.id !== ',') {
break;
}
for (;;) {
comma();
if (next_token.id !== ',') {
break;
}
next_token.warn('unexpected_a');
}
if (next_token.id === '}') {
token.warn('unexpected_a');
}
}
step_out('}', that);
return that;
});
stmt('{', function () {
next_token.warn('statement_block');
this.arity = 'statement';
this.block = statements();
this.disrupt = this.block.disrupt;
advance('}', this);
return this;
});
stmt('/*global', directive);
stmt('/*globals', directive);
stmt('/*jslint', directive);
stmt('/*member', directive);
stmt('/*members', directive);
stmt('/*property', directive);
stmt('/*properties', directive);
stmt('var', function () {
// JavaScript does not have block scope. It only has function scope. So,
// declaring a variable in a block can have unexpected consequences.
// var.first will contain an array, the array containing name tokens
// and assignment tokens.
var assign, id, name;
if (funct.loopage) {
next_token.warn('var_loop');
} else if (funct.varstatement && !option.vars) {
next_token.warn('combine_var');
}
if (funct !== global_funct) {
funct.varstatement = true;
}
this.arity = 'statement';
this.first = [];
step_in('var');
for (;;) {
name = next_token;
id = identifier(true);
define('var', name);
name.dead = funct;
if (next_token.id === '=') {
if (funct === global_funct && !name.writeable) {
name.warn('read_only');
}
assign = next_token;
assign.first = name;
spaces();
advance('=');
spaces();
if (next_token.id === 'undefined') {
token.warn('unnecessary_initialize', id);
}
if (peek(0).id === '=' && next_token.identifier) {
next_token.stop('var_a_not');
}
assign.second = expression(0);
assign.arity = 'infix';
name.init = true;
this.first.push(assign);
} else {
this.first.push(name);
}
name.dead = false;
name.writeable = true;
if (next_token.id !== ',') {
break;
}
comma();
indent.wrap = false;
if (var_mode && next_token.line === token.line &&
this.first.length === 1) {
var_mode = null;
indent.open = false;
indent.at -= option.indent;
}
spaces();
edge();
}
var_mode = null;
step_out();
return this;
});
stmt('function', function () {
one_space();
if (in_block) {
token.warn('function_block');
}
var name = next_token,
id = identifier(true);
define('var', name);
if (!name.writeable) {
name.warn('read_only');
}
name.init = true;
name.statement = true;
no_space();
this.arity = 'statement';
do_function(this, id);
if (next_token.id === '(' && next_token.line === token.line) {
next_token.stop('function_statement');
}
return this;
});
prefix('function', function (that) {
var id = optional_identifier(true), name;
if (id) {
name = token;
no_space();
} else {
id = '';
one_space();
}
do_function(that, id);
if (name) {
name.function = that.function;
}
if (funct.loopage) {
that.warn('function_loop');
}
switch (next_token.id) {
case ';':
case '(':
case ')':
case ',':
case ']':
case '}':
case ':':
case '(end)':
break;
case '.':
if (peek().string !== 'bind' || peek(1).id !== '(') {
next_token.warn('unexpected_a');
}
break;
default:
next_token.stop('unexpected_a');
}
that.arity = 'function';
return that;
});
stmt('if', function () {
var paren = next_token;
one_space();
advance('(');
step_in('control');
no_space();
edge();
this.arity = 'statement';
this.first = expected_condition(expected_relation(expression(0)));
no_space();
step_out(')', paren);
one_space();
this.block = block('if');
if (next_token.id === 'else') {
if (this.block.disrupt) {
next_token.warn(this.elif ? 'use_nested_if' : 'unnecessary_else');
}
one_space();
advance('else');
one_space();
if (next_token.id === 'if') {
next_token.elif = true;
this.else = statement(true);
} else {
this.else = block('else');
}
if (this.else.disrupt && this.block.disrupt) {
this.disrupt = true;
}
}
return this;
});
stmt('try', function () {
// try.first The catch variable
// try.second The catch clause
// try.third The finally clause
// try.block The try block
var exception_variable, paren;
one_space();
this.arity = 'statement';
this.block = block('try');
if (next_token.id === 'catch') {
one_space();
advance('catch');
one_space();
paren = next_token;
advance('(');
step_in('control');
no_space();
edge();
exception_variable = next_token;
this.first = identifier();
define('exception', exception_variable);
exception_variable.init = true;
no_space();
step_out(')', paren);
one_space();
this.second = block('catch');
if (this.second.length) {
if (this.first === 'ignore') {
exception_variable.warn('unexpected_a');
}
} else {
if (this.first !== 'ignore') {
exception_variable.warn('expected_a_b', 'ignore',
exception_variable.string);
}
}
exception_variable.dead = true;
}
if (next_token.id === 'finally') {
one_space();
advance('finally');
one_space();
this.third = block('finally');
} else if (!this.second) {
next_token.stop('expected_a_b', 'catch', artifact());
}
return this;
});
labeled_stmt('while', function () {
one_space();
var paren = next_token;
funct.loopage += 1;
advance('(');
step_in('control');
no_space();
edge();
this.arity = 'statement';
this.first = expected_relation(expression(0));
if (this.first.id !== 'true') {
expected_condition(this.first, 'unexpected_a');
}
no_space();
step_out(')', paren);
one_space();
this.block = block('while');
if (this.block.disrupt) {
prev_token.warn('strange_loop');
}
funct.loopage -= 1;
return this;
});
reserve('with');
labeled_stmt('switch', function () {
// switch.first the switch expression
// switch.second the array of cases. A case is 'case' or 'default' token:
// case.first the array of case expressions
// case.second the array of statements
// If all of the arrays of statements are disrupt, then the switch is disrupt.
var cases = [],
old_in_block = in_block,
particular,
that = token,
the_case = next_token;
function find_duplicate_case(value) {
if (are_similar(particular, value)) {
value.warn('duplicate_a');
}
}
one_space();
advance('(');
no_space();
step_in();
this.arity = 'statement';
this.first = expected_condition(expected_relation(expression(0)));
no_space();
step_out(')', the_case);
one_space();
advance('{');
step_in();
in_block = true;
this.second = [];
if (that.from !== next_token.from && !option.white) {
next_token.warn('expected_a_at_b_c', next_token.string, that.from, next_token.from);
}
while (next_token.id === 'case') {
the_case = next_token;
the_case.first = [];
the_case.arity = 'case';
for (;;) {
spaces();
edge('case');
advance('case');
one_space();
particular = expression(0);
cases.forEach(find_duplicate_case);
cases.push(particular);
the_case.first.push(particular);
if (particular.id === 'NaN') {
particular.warn('unexpected_a');
}
no_space_only();
advance(':');
if (next_token.id !== 'case') {
break;
}
}
spaces();
the_case.second = statements();
if (the_case.second && the_case.second.length > 0) {
if (!the_case.second[the_case.second.length - 1].disrupt) {
next_token.warn('missing_a_after_b', 'break', 'case');
}
} else {
next_token.warn('empty_case');
}
this.second.push(the_case);
}
if (this.second.length === 0) {
next_token.warn('missing_a', 'case');
}
if (next_token.id === 'default') {
spaces();
the_case = next_token;
the_case.arity = 'case';
edge('case');
advance('default');
no_space_only();
advance(':');
spaces();
the_case.second = statements();
if (the_case.second && the_case.second.length > 0) {
this.disrupt = the_case.second[the_case.second.length - 1].disrupt;
} else {
the_case.warn('empty_case');
}
this.second.push(the_case);
}
if (this.break) {
this.disrupt = false;
}
spaces();
step_out('}', this);
in_block = old_in_block;
return this;
});
stmt('debugger', function () {
if (!option.debug) {
this.warn('unexpected_a');
}
this.arity = 'statement';
return this;
});
labeled_stmt('do', function () {
funct.loopage += 1;
one_space();
this.arity = 'statement';
this.block = block('do');
if (this.block.disrupt) {
prev_token.warn('strange_loop');
}
one_space();
advance('while');
var paren = next_token;
one_space();
advance('(');
step_in();
no_space();
edge();
this.first = expected_condition(expected_relation(expression(0)), 'unexpected_a');
no_space();
step_out(')', paren);
funct.loopage -= 1;
return this;
});
labeled_stmt('for', function () {
var blok, filter, master, ok = false, paren = next_token, value;
this.arity = 'statement';
funct.loopage += 1;
advance('(');
if (next_token.id === ';') {
no_space();
advance(';');
no_space();
advance(';');
no_space();
advance(')');
blok = block('for');
} else {
step_in('control');
spaces(this, paren);
no_space();
if (next_token.id === 'var') {
next_token.stop('move_var');
}
edge();
if (peek(0).id === 'in') {
this.forin = true;
value = expression(1000);
master = value.master;
if (!master) {
value.stop('bad_in_a');
}
if (master.kind !== 'var' || master.function !== funct ||
!master.writeable || master.dead) {
value.warn('bad_in_a');
}
master.init = true;
master.used -= 1;
this.first = value;
advance('in');
this.second = expression(20);
step_out(')', paren);
blok = block('for');
if (!option.forin) {
if (blok.length === 1 && typeof blok[0] === 'object') {
if (blok[0].id === 'if' && !blok[0].else) {
filter = blok[0].first;
while (filter.id === '&&') {
filter = filter.first;
}
switch (filter.id) {
case '===':
case '!==':
ok = filter.first.id === '['
? are_similar(filter.first.first, this.second) &&
are_similar(filter.first.second, this.first)
: filter.first.id === 'typeof' &&
filter.first.first.id === '[' &&
are_similar(filter.first.first.first, this.second) &&
are_similar(filter.first.first.second, this.first);
break;
case '(':
ok = filter.first.id === '.' && ((
are_similar(filter.first.first, this.second) &&
filter.first.second.string === 'hasOwnProperty' &&
are_similar(filter.second[0], this.first)
) || (
filter.first.first.id === '.' &&
filter.first.first.first.first &&
filter.first.first.first.first.string === 'Object' &&
filter.first.first.first.id === '.' &&
filter.first.first.first.second.string === 'prototype' &&
filter.first.first.second.string === 'hasOwnProperty' &&
filter.first.second.string === 'call' &&
are_similar(filter.second[0], this.second) &&
are_similar(filter.second[1], this.first)
));
break;
}
} else if (blok[0].id === 'switch') {
ok = blok[0].id === 'switch' &&
blok[0].first.id === 'typeof' &&
blok[0].first.first.id === '[' &&
are_similar(blok[0].first.first.first, this.second) &&
are_similar(blok[0].first.first.second, this.first);
}
}
if (!ok) {
this.warn('for_if');
}
}
} else {
edge();
this.first = [];
for (;;) {
this.first.push(expression(0, 'for'));
if (next_token.id !== ',') {
break;
}
comma();
}
semicolon();
edge();
this.second = expected_relation(expression(0));
if (this.second.id !== 'true') {
expected_condition(this.second, 'unexpected_a');
}
semicolon(token);
if (next_token.id === ';') {
next_token.stop('expected_a_b', ')', ';');
}
this.third = [];
edge();
for (;;) {
this.third.push(expression(0, 'for'));
if (next_token.id !== ',') {
break;
}
comma();
}
no_space();
step_out(')', paren);
one_space();
blok = block('for');
}
}
if (blok.disrupt) {
prev_token.warn('strange_loop');
}
this.block = blok;
funct.loopage -= 1;
return this;
});
function optional_label(that) {
var label = next_token.string,
master;
that.arity = 'statement';
if (!funct.breakage || (!option.continue && that.id === 'continue')) {
that.warn('unexpected_a');
} else if (next_token.identifier && token.line === next_token.line) {
one_space_only();
master = scope[label];
if (!master || master.kind !== 'label') {
next_token.warn('not_a_label');
} else if (master.dead || master.function !== funct) {
next_token.warn('not_a_scope');
} else {
master.used += 1;
if (that.id === 'break') {
master.statement.break = true;
}
if (funct.breakage[funct.breakage.length - 1] === master.statement) {
next_token.warn('unexpected_a');
}
}
that.first = next_token;
advance();
} else {
if (that.id === 'break') {
funct.breakage[funct.breakage.length - 1].break = true;
}
}
return that;
}
disrupt_stmt('break', function () {
return optional_label(this);
});
disrupt_stmt('continue', function () {
return optional_label(this);
});
disrupt_stmt('return', function () {
if (funct === global_funct) {
this.warn('unexpected_a');
}
this.arity = 'statement';
if (next_token.id !== ';' && next_token.line === token.line) {
if (option.closure) {
spaces();
} else {
one_space_only();
}
if (next_token.id === '/' || next_token.id === '(regexp)') {
next_token.warn('wrap_regexp');
}
this.first = expression(0);
if (this.first.assign) {
this.first.warn('unexpected_a');
}
}
return this;
});
disrupt_stmt('throw', function () {
this.arity = 'statement';
one_space_only();
this.first = expression(20);
return this;
});
// Superfluous reserved words
reserve('class');
reserve('const');
reserve('enum');
reserve('export');
reserve('extends');
reserve('import');
reserve('super');
// Harmony reserved words
reserve('implements');
reserve('interface');
reserve('let');
reserve('package');
reserve('private');
reserve('protected');
reserve('public');
reserve('static');
reserve('yield');
// Parse JSON
function json_value() {
function json_object() {
var brace = next_token, object = Object.create(null);
advance('{');
if (next_token.id !== '}') {
while (next_token.id !== '(end)') {
while (next_token.id === ',') {
next_token.warn('unexpected_a');
advance(',');
}
if (next_token.id !== '(string)') {
next_token.warn('expected_string_a');
}
if (object[next_token.string] === true) {
next_token.warn('duplicate_a');
} else if (next_token.string === '__proto__') {
next_token.warn('dangling_a');
} else {
object[next_token.string] = true;
}
advance();
advance(':');
json_value();
if (next_token.id !== ',') {
break;
}
advance(',');
if (next_token.id === '}') {
token.warn('unexpected_a');
break;
}
}
}
advance('}', brace);
}
function json_array() {
var bracket = next_token;
advance('[');
if (next_token.id !== ']') {
while (next_token.id !== '(end)') {
while (next_token.id === ',') {
next_token.warn('unexpected_a');
advance(',');
}
json_value();
if (next_token.id !== ',') {
break;
}
advance(',');
if (next_token.id === ']') {
token.warn('unexpected_a');
break;
}
}
}
advance(']', bracket);
}
switch (next_token.id) {
case '{':
json_object();
break;
case '[':
json_array();
break;
case 'true':
case 'false':
case 'null':
case '(number)':
case '(string)':
advance();
break;
case '-':
advance('-');
no_space_only();
advance('(number)');
break;
default:
next_token.stop('unexpected_a');
}
}
// The actual JSLINT function itself.
itself = function JSLint(the_source, the_option) {
var i, predef, tree;
itself.errors = [];
itself.tree = '';
itself.properties = '';
begin = prev_token = token = next_token =
Object.create(syntax['(begin)']);
tokens = [];
predefined = Object.create(null);
add_to_predefined(standard);
property = Object.create(null);
if (the_option) {
option = Object.create(the_option);
predef = option.predef;
if (predef) {
if (Array.isArray(predef)) {
for (i = 0; i < predef.length; i += 1) {
predefined[predef[i]] = true;
}
} else if (typeof predef === 'object') {
add_to_predefined(predef);
}
}
} else {
option = Object.create(null);
}
option.indent = +option.indent || 4;
option.maxerr = +option.maxerr || 50;
global_scope = scope = Object.create(null);
global_funct = funct = {
scope: scope,
loopage: 0,
level: 0
};
functions = [funct];
block_var = [];
comments = [];
comments_off = false;
in_block = false;
indent = null;
json_mode = false;
lookahead = [];
node_js = false;
prereg = true;
strict_mode = false;
var_mode = null;
warnings = 0;
lex.init(the_source);
assume();
try {
advance();
if (next_token.id === '(number)') {
next_token.stop('unexpected_a');
} else {
switch (next_token.id) {
case '{':
case '[':
comments_off = true;
json_mode = true;
json_value();
break;
default:
// If the first token is a semicolon, ignore it. This is sometimes used when
// files are intended to be appended to files that may be sloppy. A sloppy
// file may be depending on semicolon insertion on its last line.
step_in(1);
if (next_token.id === ';' && !node_js) {
next_token.edge = true;
advance(';');
}
tree = statements();
begin.first = tree;
itself.tree = begin;
if (tree.disrupt) {
prev_token.warn('weird_program');
}
}
}
indent = null;
advance('(end)');
itself.property = property;
} catch (e) {
if (e) { // ~~
itself.errors.push({
reason : e.message,
line : e.line || next_token.line,
character : e.character || next_token.from
}, null);
}
}
return itself.errors.length === 0;
};
function unique(array) {
array = array.sort();
var i, length = 0, previous, value;
for (i = 0; i < array.length; i += 1) {
value = array[i];
if (value !== previous) {
array[length] = value;
previous = value;
length += 1;
}
}
array.length = length;
return array;
}
// Data summary.
itself.data = function () {
var data = {functions: []},
function_data,
i,
the_function,
the_scope;
data.errors = itself.errors;
data.json = json_mode;
data.global = unique(Object.keys(global_scope));
function selects(name) {
var kind = the_scope[name].kind;
switch (kind) {
case 'var':
case 'exception':
case 'label':
function_data[kind].push(name);
break;
}
}
for (i = 1; i < functions.length; i += 1) {
the_function = functions[i];
function_data = {
name: the_function.name,
line: the_function.line,
level: the_function.level,
parameter: the_function.parameter,
var: [],
exception: [],
closure: unique(the_function.closure),
outer: unique(the_function.outer),
global: unique(the_function.global),
label: []
};
the_scope = the_function.scope;
Object.keys(the_scope).forEach(selects);
function_data.var.sort();
function_data.exception.sort();
function_data.label.sort();
data.functions.push(function_data);
}
data.tokens = tokens;
return data;
};
itself.error_report = function (data) {
var evidence, i, output = [], warning;
if (data.errors.length) {
if (data.json) {
output.push('<cite>JSON: bad.</cite><br>');
}
for (i = 0; i < data.errors.length; i += 1) {
warning = data.errors[i];
if (warning) {
evidence = warning.evidence || '';
output.push('<cite>');
if (isFinite(warning.line)) {
output.push('<address>line ' +
String(warning.line) +
' character ' + String(warning.character) +
'</address>');
}
output.push(warning.reason.entityify() + '</cite>');
if (evidence) {
output.push('<pre>' + evidence.entityify() + '</pre>');
}
}
}
}
return output.join('');
};
itself.report = function (data) {
var dl, i, j, names, output = [], the_function;
function detail(h, array) {
var comma_needed = false;
if (array.length) {
output.push("<dt>" + h + "</dt><dd>");
array.forEach(function (item) {
output.push((comma_needed ? ', ' : '') + item);
comma_needed = true;
});
output.push("</dd>");
}
}
output.push('<dl class=level0>');
if (data.global.length) {
detail('global', data.global);
dl = true;
} else if (data.json) {
if (!data.errors.length) {
output.push("<dt>JSON: good.</dt>");
}
} else {
output.push("<dt><i>No new global variables introduced.</i></dt>");
}
if (dl) {
output.push("</dl>");
} else {
output[0] = '';
}
if (data.functions) {
for (i = 0; i < data.functions.length; i += 1) {
the_function = data.functions[i];
names = [];
if (the_function.params) {
for (j = 0; j < the_function.params.length; j += 1) {
names[j] = the_function.params[j].string;
}
}
output.push('<dl class=level' + the_function.level +
'><address>line ' + String(the_function.line) +
'</address>' + the_function.name.entityify());
detail('parameter', the_function.parameter);
detail('variable', the_function.var);
detail('exception', the_function.exception);
detail('closure', the_function.closure);
detail('outer', the_function.outer);
detail('global', the_function.global);
detail('label', the_function.label);
output.push('</dl>');
}
}
return output.join('');
};
itself.properties_report = function (property) {
if (!property) {
return '';
}
var i,
key,
keys = Object.keys(property).sort(),
mem = ' ',
name,
not_first = false,
output = ['/*properties'];
for (i = 0; i < keys.length; i += 1) {
key = keys[i];
if (property[key] > 0) {
if (not_first) {
mem += ',';
}
name = ix.test(key)
? key
: '\'' + key.replace(nx, sanitize) + '\'';
if (mem.length + name.length >= 80) {
output.push(mem);
mem = ' ';
} else {
mem += ' ';
}
mem += name;
not_first = true;
}
}
output.push(mem, '*/\n');
return output.join('\n');
};
itself.color = function (data) {
var from,
i = 1,
level,
line,
result = [],
thru,
data_token = data.tokens[0];
while (data_token && data_token.id !== '(end)') {
from = data_token.from;
line = data_token.line;
thru = data_token.thru;
level = data_token.function.level;
do {
thru = data_token.thru;
data_token = data.tokens[i];
i += 1;
} while (data_token && data_token.line === line &&
data_token.from - thru < 5 &&
level === data_token.function.level);
result.push({
line: line,
level: level,
from: from,
thru: thru
});
}
return result;
};
itself.jslint = itself;
itself.edition = '2014-04-08';
return itself;
}());
exports.JSLINT = JSLINT; |
import { mustBeNumber } from '../checks/mustBeNumber';
import { Color } from '../core/Color';
import { GraphicsProgramSymbols } from '../core/GraphicsProgramSymbols';
/**
* Sets the 'uColor' uniform to the color RGB value.
*/
var ColorFacet = /** @class */ (function () {
/**
* @param uColorName The name of the WebL uniform that this facet will affect.
*/
function ColorFacet(uColorName) {
if (uColorName === void 0) { uColorName = GraphicsProgramSymbols.UNIFORM_COLOR; }
this.uColorName = uColorName;
/**
*
*/
this.color = Color.fromRGB(1, 1, 1);
}
Object.defineProperty(ColorFacet.prototype, "r", {
/**
* The red component of the color.
*/
get: function () {
return this.color.r;
},
set: function (r) {
mustBeNumber('r', r);
this.color.r = r;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorFacet.prototype, "g", {
/**
* The green component of the color.
*/
get: function () {
return this.color.g;
},
set: function (g) {
mustBeNumber('g', g);
this.color.g = g;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorFacet.prototype, "b", {
/**
* The blue component of the color.
*/
get: function () {
return this.color.b;
},
set: function (b) {
mustBeNumber('b', b);
this.color.b = b;
},
enumerable: false,
configurable: true
});
ColorFacet.prototype.scaleRGB = function (α) {
this.r *= α;
this.g *= α;
this.b *= α;
return this;
};
ColorFacet.prototype.setRGB = function (r, g, b) {
this.r = r;
this.g = g;
this.b = b;
return this;
};
/**
*
*/
ColorFacet.prototype.setUniforms = function (visitor) {
var uColorName = this.uColorName;
if (uColorName) {
var color = this.color;
visitor.uniform3f(uColorName, color.r, color.g, color.b);
}
};
/**
* @hidden
*/
ColorFacet.PROP_RGB = 'rgb';
/**
* @hidden
*/
ColorFacet.PROP_RED = 'r';
/**
* @hidden
*/
ColorFacet.PROP_GREEN = 'g';
/**
* @hidden
*/
ColorFacet.PROP_BLUE = 'b';
return ColorFacet;
}());
export { ColorFacet };
|
(function($, UI) {
"use strict";
var $win = $(window),
$doc = $(document),
Offcanvas = {
show: function(element) {
element = $(element);
if (!element.length) return;
var doc = $("html"),
bar = element.find(".uk-offcanvas-bar:first"),
rtl = ($.UIkit.langdirection == "right"),
dir = (bar.hasClass("uk-offcanvas-bar-flip") ? -1 : 1) * (rtl ? -1 : 1),
scrollbar = dir == -1 && $win.width() < window.innerWidth ? (window.innerWidth - $win.width()) : 0;
scrollpos = {x: window.scrollX, y: window.scrollY};
element.addClass("uk-active");
doc.css({"width": window.innerWidth, "height": window.innerHeight}).addClass("uk-offcanvas-page");
doc.css((rtl ? "margin-right" : "margin-left"), (rtl ? -1 : 1) * ((bar.outerWidth() - scrollbar) * dir)).width(); // .width() - force redraw
bar.addClass("uk-offcanvas-bar-show").width();
element.off(".ukoffcanvas").on("click.ukoffcanvas swipeRight.ukoffcanvas swipeLeft.ukoffcanvas", function(e) {
var target = $(e.target);
if (!e.type.match(/swipe/)) {
if (!target.hasClass("uk-offcanvas-close")) {
if (target.hasClass("uk-offcanvas-bar")) return;
if (target.parents(".uk-offcanvas-bar:first").length) return;
}
}
e.stopImmediatePropagation();
Offcanvas.hide();
});
$doc.on('keydown.ukoffcanvas', function(e) {
if (e.keyCode === 27) { // ESC
Offcanvas.hide();
}
});
},
hide: function(force) {
var doc = $("html"),
panel = $(".uk-offcanvas.uk-active"),
rtl = ($.UIkit.langdirection == "right"),
bar = panel.find(".uk-offcanvas-bar:first");
if (!panel.length) return;
if ($.UIkit.support.transition && !force) {
doc.one($.UIkit.support.transition.end, function() {
doc.removeClass("uk-offcanvas-page").css({"width": "", "height": ""});
panel.removeClass("uk-active");
window.scrollTo(scrollpos.x, scrollpos.y);
}).css((rtl ? "margin-right" : "margin-left"), "");
setTimeout(function(){
bar.removeClass("uk-offcanvas-bar-show");
}, 50);
} else {
doc.removeClass("uk-offcanvas-page").css({"width": "", "height": ""});
panel.removeClass("uk-active");
bar.removeClass("uk-offcanvas-bar-show");
window.scrollTo(scrollpos.x, scrollpos.y);
}
panel.off(".ukoffcanvas");
$doc.off(".ukoffcanvas");
}
}, scrollpos;
var OffcanvasTrigger = function(element, options) {
var $this = this,
$element = $(element);
if($element.data("offcanvas")) return;
this.options = $.extend({
"target": $element.is("a") ? $element.attr("href") : false
}, options);
this.element = $element;
$element.on("click", function(e) {
e.preventDefault();
Offcanvas.show($this.options.target);
});
this.element.data("offcanvas", this);
};
OffcanvasTrigger.offcanvas = Offcanvas;
UI["offcanvas"] = OffcanvasTrigger;
// init code
$doc.on("click.offcanvas.uikit", "[data-uk-offcanvas]", function(e) {
e.preventDefault();
var ele = $(this);
if (!ele.data("offcanvas")) {
var obj = new OffcanvasTrigger(ele, UI.Utils.options(ele.attr("data-uk-offcanvas")));
ele.trigger("click");
}
});
})(jQuery, jQuery.UIkit); |
var BaseCrm = require('../index');
var base = new BaseCrm('<YOUR_TOKEN_HERE>');
base.get('/contacts/').then(function(success) {
console.log(success);
}, function(failed) {
}); |
module.exports = {
'env': {
'browser': true,
'commonjs': true,
'es2020': true,
'node': true,
'jest': true,
},
'extends': 'eslint:recommended',
'parserOptions': {
'ecmaVersion': 11
},
'rules': {
'accessor-pairs': 'error',
'array-bracket-newline': 'off',
'array-bracket-spacing': 'off',
'array-callback-return': 'error',
'array-element-newline': 'off',
'arrow-body-style': 'off',
'arrow-parens': 'off',
'arrow-spacing': [
'error',
{
'after': true,
'before': true
}
],
'block-scoped-var': 'error',
'block-spacing': 'error',
'brace-style': 'off',
'callback-return': 'off',
'camelcase': 'error',
'capitalized-comments': 'off',
'class-methods-use-this': 'off',
'comma-dangle': 'off',
'comma-spacing': [
'error',
{
'after': true,
'before': false
}
],
'comma-style': 'error',
'complexity': 'error',
'computed-property-spacing': 'error',
'consistent-return': 'off',
'consistent-this': 'error',
'curly': 'error',
'default-case': 'error',
'default-case-last': 'error',
'default-param-last': 'error',
'dot-location': 'off',
'dot-notation': 'error',
'eol-last': 'error',
'eqeqeq': 'error',
'func-call-spacing': 'error',
'func-name-matching': 'error',
'func-names': 'off',
'func-style': 'error',
'function-paren-newline': 'off',
'generator-star-spacing': 'error',
'global-require': 'off',
'grouped-accessor-pairs': 'error',
'guard-for-in': 'error',
'handle-callback-err': 'error',
'id-blacklist': 'error',
'id-length': 'off',
'id-match': 'error',
'implicit-arrow-linebreak': 'error',
'indent': 'off',
'indent-legacy': 'off',
'init-declarations': 'error',
'jsx-quotes': 'error',
'key-spacing': 'error',
'keyword-spacing': 'error',
'line-comment-position': 'off',
'linebreak-style': [
'error',
'unix'
],
'lines-around-comment': 'off',
'lines-around-directive': 'error',
'lines-between-class-members': 'warn',
'max-classes-per-file': 'off',
'max-depth': 'error',
'max-len': 'off',
'max-lines': 'off',
'max-lines-per-function': 'off',
'max-nested-callbacks': 'error',
'max-params': 'off',
'max-statements': 'off',
'max-statements-per-line': 'error',
'multiline-comment-style': [
'error',
'separate-lines'
],
'multiline-ternary': 'off',
'new-cap': 'error',
'new-parens': 'error',
'newline-after-var': [
'off',
'always'
],
'newline-before-return': 'off',
'newline-per-chained-call': 'off',
'no-alert': 'error',
'no-array-constructor': 'error',
'no-await-in-loop': 'error',
'no-bitwise': 'error',
'no-buffer-constructor': 'error',
'no-caller': 'error',
'no-case-declarations': 'off',
'no-catch-shadow': 'error',
'no-confusing-arrow': 'error',
'no-console': 'off',
'no-constructor-return': 'warn',
'no-continue': 'error',
'no-div-regex': 'error',
'no-duplicate-imports': 'error',
'no-else-return': 'error',
'no-empty-function': 'off',
'no-eq-null': 'error',
'no-eval': 'error',
'no-extend-native': 'error',
'no-extra-bind': 'error',
'no-extra-label': 'error',
'no-extra-parens': 'off',
'no-floating-decimal': 'error',
'no-implicit-coercion': 'off',
'no-implicit-globals': 'warn',
'no-implied-eval': 'error',
'no-inline-comments': 'off',
'no-invalid-this': 'error',
'no-iterator': 'error',
'no-label-var': 'error',
'no-labels': 'error',
'no-lone-blocks': 'error',
'no-lonely-if': 'error',
'no-loop-func': 'error',
'no-loss-of-precision': 'error',
'no-magic-numbers': 'off',
'no-mixed-operators': 'off',
'no-mixed-requires': 'off',
'no-multi-assign': 'error',
'no-multi-spaces': 'error',
'no-multi-str': 'error',
'no-multiple-empty-lines': 'error',
'no-native-reassign': 'error',
'no-negated-condition': 'error',
'no-negated-in-lhs': 'error',
'no-nested-ternary': 'error',
'no-new': 'error',
'no-new-func': 'error',
'no-new-object': 'error',
'no-new-require': 'error',
'no-new-wrappers': 'error',
'no-octal-escape': 'error',
'no-param-reassign': 'off',
'no-path-concat': 'error',
'no-plusplus': 'error',
'no-process-env': 'off',
'no-process-exit': 'error',
'no-promise-executor-return': 'off',
'no-proto': 'error',
'no-restricted-exports': 'error',
'no-restricted-globals': 'error',
'no-restricted-imports': 'error',
'no-restricted-modules': 'error',
'no-restricted-properties': 'error',
'no-restricted-syntax': 'error',
'no-return-assign': 'error',
'no-return-await': 'error',
'no-script-url': 'error',
'no-self-compare': 'error',
'no-sequences': 'error',
'no-shadow': 'warn',
'no-spaced-func': 'error',
'no-sync': 'off',
'no-tabs': 'off',
'no-template-curly-in-string': 'error',
'no-ternary': 'off',
'no-throw-literal': 'error',
'no-trailing-spaces': 'error',
'no-undef-init': 'error',
'no-undefined': 'error',
'no-underscore-dangle': 'error',
'no-unmodified-loop-condition': 'error',
'no-unneeded-ternary': 'error',
'no-unreachable-loop': 'error',
'no-unused-expressions': 'warn',
'no-use-before-define': 'error',
'no-useless-backreference': 'error',
'no-useless-call': 'error',
'no-useless-computed-key': 'error',
'no-useless-concat': 'error',
'no-useless-constructor': 'error',
'no-useless-rename': 'error',
'no-useless-return': 'error',
'no-var': 'error',
'no-void': 'error',
'no-warning-comments': 'off',
'no-whitespace-before-property': 'error',
'nonblock-statement-body-position': 'error',
'object-curly-newline': 'error',
'object-curly-spacing': [
'error',
'always'
],
'object-shorthand': 'error',
'one-var': 'off',
'one-var-declaration-per-line': 'error',
'operator-assignment': 'error',
'operator-linebreak': 'off',
'padded-blocks': 'off',
'padding-line-between-statements': 'error',
'prefer-arrow-callback': 'off',
'prefer-const': 'off',
'prefer-destructuring': 'off',
'prefer-exponentiation-operator': 'error',
'prefer-named-capture-group': 'error',
'prefer-numeric-literals': 'error',
'prefer-object-spread': 'off',
'prefer-promise-reject-errors': 'error',
'prefer-reflect': 'error',
'prefer-regex-literals': 'error',
'prefer-rest-params': 'error',
'prefer-spread': 'off',
'prefer-template': 'error',
'quote-props': 'off',
'quotes': [
'warn',
'single',
{
'allowTemplateLiterals': true
}
],
'radix': 'error',
'require-atomic-updates': 'error',
'require-await': 'error',
'require-jsdoc': 'error',
'require-unicode-regexp': 'warn',
'rest-spread-spacing': 'error',
'semi': 'error',
'semi-spacing': 'error',
'semi-style': [
'error',
'last'
],
'sort-imports': 'error',
'sort-keys': 'off',
'sort-vars': 'error',
'space-before-blocks': 'error',
'space-before-function-paren': 'off',
'space-in-parens': 'off',
'space-infix-ops': 'error',
'space-unary-ops': 'error',
'spaced-comment': [
'error',
'always'
],
'strict': [
'error',
'never'
],
'switch-colon-spacing': 'error',
'symbol-description': 'error',
'template-curly-spacing': 'error',
'template-tag-spacing': 'error',
'unicode-bom': [
'error',
'never'
],
'vars-on-top': 'error',
'wrap-iife': 'error',
'wrap-regex': 'error',
'yield-star-spacing': 'error',
'yoda': [
'error',
'never'
]
}
};
|
/**
* Adds vendor prefixes to CSS
*
* @note Attention: Autoprefixer removes embedded sourcemaps!
* @version 1.0.1
* @author Matthias Morin <mat@tangoman.io>
*/
/**
* Handles errors without stopping watch
*
* @param {Object} err Received error
* @url https://github.com/gulpjs/gulp/issues/259
*/
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
// https://www.npmjs.com/package/gulp-autoprefixer
// https://www.npmjs.com/package/gulp-plumber
module.exports = function(gulp, plugins, config){
return function(cb){
console.log('\r\n\r\n----------> Prefixing CSS');
/**
* Autoprefixer Config
* @type {Object}
* @url https://github.com/postcss/autoprefixer#options
* @url https://github.com/ai/browserslist#queries
*/
var objOptions = {
browsers: [
'> 1%',
'last 2 versions',
'Android 2.3',
'Android >= 4',
'Chrome >= 20',
'Firefox >= 24',
'Explorer >= 8',
'iOS >= 6',
'Opera >= 12',
'Safari >= 6',
],
cascade: true,
add: true,
remove: true,
supports: true,
flexbox: true,
grid: true,
};
gulp.src(config.src.css + '/*.css')
.pipe(plugins.plumber({ errorHandler: handleError }))
.pipe(plugins.autoprefixer(objOptions))
.pipe(gulp.dest(config.src.css))
.pipe(gulp.dest(config.dest.css))
.on('end', cb);
};
};
|
/**
* Created by qh4r on 22.10.15.
*/
var bookController = function (Book, Review) {
var fetchBook = function (req, res, next) {
next();
};
var post = function (req, res) {
//var book = Book.create(req.body);
if (!req.body.title) {
res.status(400);
res.send('Title is required');
}
else {
Book.create(req.body).then(function (err, result) {
res.status(201);
res.json(result);
}).catch(function (err) {
return res.status(599).json(err);
});
}
};
var getAll = function (req, res) {
var query = {};
if (req.query) {
if (req.query.genre) query.genre = req.query.genre;
if (req.query.author)query.author = req.query.author;
if (req.query.title)query.title = req.query.title;
if (req.query.read)query.read = req.query.read;
}
Book.findAll(query).then(function (err, result) {
if (err)return res.status(599).json([err]);
var booksList = [];
result.forEach(function (book, index, array) {
//to escape mongoose model validation and ger simple object
var newBook = book.toJSON();
newBook.links = {};
newBook.links.self = 'http://' + req.headers.host + '/api/books/' + book.id;
booksList.push(newBook);
});
res.status(200).json(booksList);
});
};
var getSingle = function (req, res) {
console.log(req.book);
Book.find({
where: {id: req.params.bookId},
include: [Review]
})
.then(function (err, book) {
if (err)return res.status(599).json([err]);
if (book) {
res.status(200).json(req.book);
} else {
res.status(404).json({"error": "No book found"});
}
});
};
var put = function (req, res) {
if (req.body.id) {
delete req.body.id;
}
var book = {};
console.log(book);
book.title = req.body.title;
book.author = req.body.author;
book.genre = req.body.genre;
book.read = req.body.read;
console.log(book);
Book.update(book, {
where: {
id: req.params.bookId
}
}).then(function (err) {
if (err) {
console.log(book);
return res.status(599).json(err);
}
console.log(book);
res.status(201).json(req.book);
}).catch(function (e) {
console.log(e.message);
});
};
var patch = function (req, res) {
//req.book.title = req.body.title || req.book.title;
//req.book.author = req.body.author || req.book.author;
//req.book.genre = req.body.genre || req.book.genre;
//req.book.result = req.body.result || req.book.result;
if (req.body._id) {
delete req.body._id;
}
var book = {};
console.log(book);
for (var x in req.body) {
book[x] = req.body[x];
}
console.log(book);
Book.update(book, {
where: {
id: req.params.bookId
}
}).then(function (err) {
if (err) {
console.log(book);
res.status(599).json(err);
}
console.log(book);
res.status(201).json(req.book);
}).catch(function (e) {
console.log(e.message);
});
};
var deleteBook = function (req, res) {
Book.destroy({
where: {id: req.params.bookId}
})
.then(function () {
res.status(204).json({message: "book removed"});
}).catch(function (err) {
return res.status(500).json(err);
});
};
var addReview = function (req, res) {
var review = {}
for(var prop in req.body){
review[prop] = req.body[prop];
}
if (!review.author) {
return res.status(400).json({error: new Error("wrong input")})
}
review.Book_FK = req.params.bookId;
console.log(review);
Review.create(review).then(function () {
res.status(201).json(review);
}).catch(function (err) {
return res.status(599).json(err)
});
};
return {
post: post,
getAll: getAll,
getSingle: getSingle,
put: put,
patch: patch,
delete: deleteBook,
fetchBook: fetchBook,
addReview: addReview
};
};
module.exports = bookController; |
import foo from "foo";
export default async function bar() {
await foo();
}
|
const styles = {
listNumber: {
position: 'absolute',
top: 'inherit',
right: '16px',
},
redBackground: {
backgroundColor: 'rgba(183, 28, 28,0.3)',
},
};
export default styles;
|
xtag.register("m-image", {
mixins: ["m-element"],
content: "<div class='image'></div>",
lifecycle: {
created: function () {
this.imageView = this.querySelector("div.image");
this.loader = new Image();
this.render();
}
},
accessors: {
src: {
attribute: {},
get: function () {
return this._src;
},
set: function (value) {
this._src = value;
// Loader for the image
var component = this;
this.loader.addEventListener("load", function () {
component.imageView.style.backgroundImage = "url('" + value + "')";
component.imageView.classList.add("show");
});
this.loader.src = value;
}
}
},
methods: {
render: function () {
this.style.backgroundColor = colors[this.tint in colors ? this.tint : "grey"][400];
}
}
}); |
module.exports = function gruntInit(grunt) {
grunt.initConfig({
babel: {
options: {plugins: ['transform-es2015-modules-commonjs']},
server: {files: [{cwd: 'src/', dest: 'dist', expand: true, ext: '.js', src: ['**/*.js']}]}
},
browserSync: {
bsFiles: {src: ['dist/client/**/*', 'bower_components']},
options: {
server: {baseDir: './dist/client/', routes: {'/bower_components': 'bower_components'}, watchTask: true}
}
},
concurrent: {
client: ['nodemon', 'watch', 'browserSync'],
server: ['nodemon', 'watch'],
options: {logConcurrentOutput: true}
},
copy: {
dist: {
files: [
{expand: true, cwd: 'src/client/modules', src: ['./**/assets/**/*.svg'], dest: 'dist/client/modules'}
]
}
},
eslint: {target: ['src/**/*.js']},
flow: {files: {}},
minifyHtml: {dist: {files: grunt.file.expandMapping('**/*.html', 'dist/client/', {cwd: 'src/client'})}},
nodemon: {
dev: {
script: 'dist/server/index.js',
options: {args: ['dev'], env: {PORT: 9000}, nodeArgs: ['--debug'], watch: ['dist'], legacyWatch: true}
}
},
sass: {
dist: {
files: {
'dist/client/assets/main.css': 'src/client/assets/main.scss',
'dist/client/modules/sidebar/assets/sidebar.css': 'src/client/modules/sidebar/assets/sidebar.scss'
},
options: {compass: true, sourcemap: 'inline', unixNewlines: true}
}
},
watch: {
client: {files: 'src/client/**/*', tasks: ['minifyHtml', 'sass', 'copy']},
server: {files: 'src/server/**/*.js', tasks: ['build:server']}
}
});
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-flow');
grunt.loadNpmTasks('grunt-minify-html');
grunt.loadNpmTasks('grunt-nodemon');
grunt.registerTask('check', ['eslint', 'flow']);
grunt.registerTask('build:client', ['minifyHtml', 'sass', 'copy']);
grunt.registerTask('build:server', ['babel']);
grunt.registerTask('build', ['build:server', 'build:client']);
grunt.registerTask('develop:client', ['build', 'concurrent:client']);
grunt.registerTask('develop:server', ['build:server', 'concurrent:server']);
};
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
var fs = require('fs'),
path = require('path'),
cordovaServe = require('cordova-serve'),
pluginMapper = require('cordova-registry-mapper').oldToNew,
config = require('./config'),
dirs = require('./dirs'),
telemetry = require('./telemetryHelper');
var pluginSimulationFiles = require('./plugin-files');
var plugins = {};
var pluginsTelemetry = {
simulatedBuiltIn: [],
simulatedNonBuiltIn: [],
notSimulated: []
};
var _router;
function initPlugins() {
// Always defined plugins
var pluginList = ['exec', 'events'];
var pluginPath = path.resolve(config.platformRoot, 'plugins');
if (fs.existsSync(pluginPath)) {
fs.readdirSync(pluginPath).forEach(function (file) {
if (fs.statSync(path.join(pluginPath, file)).isDirectory()) {
pluginList.push(file);
}
});
}
if (pluginList.indexOf('cordova-plugin-geolocation') === -1) {
pluginList.push('cordova-plugin-geolocation');
}
var projectRoot = config.projectRoot;
plugins = {};
pluginsTelemetry.simulatedBuiltIn = [];
pluginsTelemetry.simulatedNonBuiltIn = [];
pluginsTelemetry.notSimulated = [];
pluginList.forEach(function (pluginId) {
var pluginFilePath = findPluginPath(projectRoot, pluginId);
if (pluginFilePath) {
plugins[pluginId] = pluginFilePath;
if (pluginFilePath.indexOf(dirs.plugins) === 0) {
pluginsTelemetry.simulatedBuiltIn.push(pluginId);
} else {
pluginsTelemetry.simulatedNonBuiltIn.push(pluginId);
}
} else {
pluginsTelemetry.notSimulated.push(pluginId);
}
});
telemetry.sendTelemetry('plugins', { simulatedBuiltIn: pluginsTelemetry.simulatedBuiltIn }, { simulatedNonBuiltIn: pluginsTelemetry.simulatedNonBuiltIn, notSimulated: pluginsTelemetry.notSimulated });
addPlatformDefaultHandlers();
populateRouter();
}
function populateRouter() {
var router = getRouter();
router.stack = [];
Object.keys(plugins).forEach(function (plugin) {
router.use('/simulator/plugin/' + plugin, cordovaServe.static(plugins[plugin]));
});
}
/**
* Adds platform specific exec handlers and ui components to the main plugins list so
* that they are injected to simulation host along with standard plugins
*/
function addPlatformDefaultHandlers() {
var platform = config.platform;
var platformScriptsRoot = path.join(dirs.platforms, platform);
if (fs.existsSync(platformScriptsRoot)) {
var pluginId = platform + '-platform-core';
plugins[pluginId] = platformScriptsRoot;
}
}
function findPluginPath(projectRoot, pluginId, hostType) {
if (!hostType) {
return findPluginPath(projectRoot, pluginId, 'sim-host') || findPluginPath(projectRoot, pluginId, 'app-host');
}
for (var file in pluginSimulationFiles[hostType]) {
var pluginFilePath = findPluginSourceFilePath(projectRoot, pluginId, pluginSimulationFiles[hostType][file]);
if (pluginFilePath) {
return pluginFilePath;
}
}
}
function findPluginSourceFilePath(projectRoot, pluginId, file) {
// Look in the plugin itself
var pluginPath = path.join(projectRoot, 'plugins', pluginId, 'src/simulation');
var pluginFilePath = path.resolve(pluginPath, file);
return fs.existsSync(pluginFilePath) ? pluginPath : findBuiltInPluginSourceFilePath(pluginId, file);
}
function findBuiltInPluginSourceFilePath(pluginId, file) {
var pluginPath = path.join(dirs.plugins, pluginId);
var pluginFilePath = path.join(pluginPath, file);
if (fs.existsSync(pluginFilePath)) {
return pluginPath;
}
// In case plugin id is in old style, try mapping to new style to see if we have support for that.
pluginId = pluginMapper[pluginId];
return pluginId ? findBuiltInPluginSourceFilePath(pluginId, file) : null;
}
function getRouter() {
_router = _router || cordovaServe.Router();
return _router;
}
module.exports.initPlugins = initPlugins;
module.exports.getRouter = getRouter;
module.exports.getPlugins = function () {
return plugins;
};
module.exports.getPluginsTelemetry = function () {
return pluginsTelemetry;
};
|
var expect = chai.expect;
describe('Fidem provider', function () {
var fidem, $httpBackend, $window, $rootScope, $q, $timeout, interceptors,
logAction, expectRequest;
beforeEach(module('fidem', function (fidemProvider, $provide) {
fidemProvider.setApiEndpoint('http://services.fidemapps.com');
fidemProvider.setApiKey('myApiKey');
interceptors = fidemProvider.interceptors;
$provide.value('$window', {
config: 'myConfig',
navigator: {}
});
}));
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
fidem = $injector.get('fidem');
$window = $injector.get('$window');
$rootScope = $injector.get('$rootScope');
$q = $injector.get('$q');
$timeout = $injector.get('$timeout');
$httpBackend.whenPUT('http://services.fidemapps.com/api/members/MEMBER_ID/link/LINK_MEMBER_ID')
.respond(200, {});
linkMembers = function (memberId, linkMemberId, reason, done) {
fidem.linkMembers(memberId, linkMemberId, reason).then(function () {
done();
});
$rootScope.$digest();
};
expectRequest = function (data) {
$httpBackend.expectPUT(
'http://services.fidemapps.com/api/members/MEMBER_ID/link/LINK_MEMBER_ID',
data,
function (headers) {
return headers['X-Fidem-AccessApiKey'] === 'myApiKey';
}
);
};
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('call addLinkMembers', function () {
it('should assign link members', function (done) {
expectRequest({"link_reason": "LINK_REASON"});
linkMembers('MEMBER_ID', 'LINK_MEMBER_ID', 'LINK_REASON', done);
$httpBackend.flush();
});
});
}); |
function JojoExecutionThread(id, { useId, config, args, onMessages, onError, onClose }) {
const env = Object.create(process.env);
env['RAILS_ENV'] = 'test';
if (useId) {
env['TEST_ENV_NUMBER'] = id;
}
let fd = JojoExecutionThread.spawn(config.rspecBinary, args, {
detached: false,
stdio: 'pipe',
env: env,
cwd: config.root
});
let dataBuf = '';
let errBuf = '';
fd.stdout.on('data', function(chunk) {
const payload = parseMessages(dataBuf + chunk.toString());
if (payload.messages.length) {
onMessages(payload.messages);
}
dataBuf = payload.trailing;
});
fd.stderr.on('data', function(chunk) {
errBuf += chunk;
});
fd.on('exit', function(exitCode) {
if (errBuf.match(/ActiveRecord::NoDatabaseError/)) {
throw new Error(
errBuf + '\n' +
Array(80).join('-') +
"\n" +
"This error likely means you have not created a database to use " +
"for this thread." +
"\nTo do this, run the following command and try again:" +
"\n\n" +
" RAILS_ENV=test TEST_ENV_NUMBER=" + id + " ./bin/rake db:setup" +
"\n"
);
}
else if (errBuf.length) {
onError(errBuf);
}
fd = null;
onClose(exitCode);
});
return fd;
}
JojoExecutionThread.spawn = require('child_process').spawn;
module.exports = JojoExecutionThread;
function parseMessages(buffer) {
const lines = buffer.split('\n');
const messages = lines.map(function(rawChunk) {
const chunk = rawChunk.trim();
if (chunk.length === 0) {
return false;
}
try {
return JSON.parse(chunk);
}
catch (e) {
console.log(e.message);
console.log(chunk);
return null;
}
});
return {
trailing: lines.filter(function(_, index) {
return messages[index] === null;
}).join('\n'),
messages: messages.filter(m => !!m)
};
}
|
function apartamentoDescricao (local, quartos, garagem) {
this.local = local,
this.quartos = quartos,
this.garagem = garagem
};
function apartamentoVenda (local, quantidade, vendidos) {
this.local = local,
this.quantidade = quantidade,
this.vendidos = vendidos
};
zonaSulDescricao = new apartamentoDescricao('Zona Sul', 4, 'Sim');
zonaSulVenda = new apartamentoVenda('Zona Sul', 12, 7);
console.log(
zonaSulDescricao.local + '\n'
+ zonaSulDescricao.quartos + '\n'
+ zonaSulDescricao.garagem + '\n'
+ zonaSulVenda.local + '\n'
+ zonaSulVenda.quantidade + '\n'
+ zonaSulVenda.vendidos
);
// Agora a mesma função mesclando os argumentos com o metodo call(this, args);
function apartamentoDescricao (local, quartos, garagem) {
this.local = local,
this.quartos = quartos,
this.garagem = garagem
};
function apartamentoVenda (local, quartos, garagem, quantidade, vendidos) {
this.local = local,
this.quantidade = quantidade,
this.vendidos = vendidos,
apartamentoDescricao.call(this, local, quartos, garagem);
};
zonaSul = new apartamentoVenda('Zona Sul', 4, 'Sim', 12, 7);
window.onload = function () {
console.log(
zonaSul.local + '\n'
+ zonaSul.quartos + '\n'
+ zonaSul.garagem + '\n'
+ zonaSul.local + '\n'
+ zonaSul.quantidade + '\n'
+ zonaSul.vendidos
);
};
|
/**
* Logux error in logs synchronization.
*
* @param {string} type The error code.
* @param {any} options The error option.
* @param {boolean} [received=false] Was error received from remote node.
*
* @example
* if (error.name === 'LoguxError') {
* console.log('Server throws: ' + error.description)
* }
*
* @extends Error
* @class
*/
function LoguxError (type, options, received) {
Error.call(this, type)
/**
* Always equal to `LoguxError`. The best way to check error class.
* @type {string}
*
* @example
* if (error.name === 'LoguxError') { }
*/
this.name = 'LoguxError'
/**
* The error code.
* @type {string}
*
* @example
* if (error.type === 'timeout') {
* fixNetwork()
* }
*/
this.type = type
/**
* Error options depends on error type.
* @type {any}
*
* @example
* if (error.type === 'timeout') {
* console.error('A timeout was reached (' + error.options + ' ms)')
* }
*/
this.options = options
/**
* Human-readable error description.
* @type {string}
*
* @example
* console.log('Server throws: ' + error.description)
*/
this.description = LoguxError.describe(type, options)
/**
* Was error received from remote client.
* @type {boolean}
*/
this.received = !!received
this.message = ''
if (received) {
this.message += 'Logux received ' + this.type + ' error'
if (this.description !== this.type) {
this.message += ' (' + this.description + ')'
}
} else {
this.message = this.description
}
if (Error.captureStackTrace) {
Error.captureStackTrace(this, LoguxError)
}
}
/**
* Return a error description by it code.
*
* @param {string} type The error code.
* @param {any} options The errors options depends on error code.
*
* @return {string} Human-readable error description.
*
* @example
* errorMessage(msg) {
* console.log(LoguxError.describe(msg[1], msg[2]))
* }
*/
LoguxError.describe = function describe (type, options) {
if (type === 'timeout') {
return 'A timeout was reached (' + options + 'ms)'
} else if (type === 'wrong-format') {
return 'Wrong message format in ' + options
} else if (type === 'unknown-message') {
return 'Unknown message `' + options + '` type'
} else if (type === 'bruteforce') {
return 'Too many wrong authentication attempts'
} else if (type === 'wrong-protocol') {
return 'Logux supports protocols only from version ' + options.supported +
', but you use ' + options.used
} else if (type === 'wrong-subprotocol') {
return 'Only ' + options.supported + ' application subprotocols are ' +
'supported, but you use ' + options.used
} else if (type === 'wrong-credentials') {
return 'Wrong credentials'
} else {
return type
}
}
LoguxError.prototype = Error.prototype
module.exports = LoguxError
|
function assertKeyValue(actualValue, expectedValue) {
if (arguments.length > 1) return actualValue === expectedValue;
return typeof actualValue !== 'undefined';
}
export default assertKeyValue;
|
'use strict';
import Knex from 'knex';
import validator from 'validator';
import md5 from 'md5';
import configs from '../configs/index';
const knex = Knex(configs.knexConfig);
export default class StudyPlan{
//新建大事件
static async create(req, res){
let result;
try{
result = await knex('core_user_study_plan').insert(req);
}catch(error){
console.log(error);
}
if(result[0]){
result = 'success';
}
return result;
}
//查找用户id
static async findByName(req, res){
let result;
try{
result = await knex('core_account')
.select('id')
.where('username', req);
}catch(error){
console.log(error);
}
return result;
}
} |
import React from 'react'
import Background from './parts/Background';
const Splash = () => (
<div>
<Background />
</div>
)
export default Splash
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _boom = require('boom');
var _boom2 = _interopRequireDefault(_boom);
var _elasticsearch = require('elasticsearch');
var _elasticsearch2 = _interopRequireDefault(_elasticsearch);
var _elasticsearchHapiLogger = require('elasticsearch-hapi-logger');
var _elasticsearchHapiLogger2 = _interopRequireDefault(_elasticsearchHapiLogger);
var _package = require('../package.json');
var _package2 = _interopRequireDefault(_package);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var register = function register(server, options, next) {
var es = new _elasticsearch2.default.Client(_extends({
log: new _elasticsearchHapiLogger2.default(server)
}, options));
server.ext('onPostHandler', function (request, reply) {
var response = request.response;
if (response instanceof _elasticsearch2.default.errors.ConnectionFault) {
return reply(_boom2.default.clientTimeout(response.message));
}
if (response instanceof _elasticsearch2.default.errors.NoConnections) {
return reply(_boom2.default.clientTimeout(response.message));
}
if (response instanceof _elasticsearch2.default.errors.RequestTimeout) {
return reply(_boom2.default.gatewayTimeout(response.message));
}
if (response instanceof _elasticsearch2.default.errors.ServiceUnavailable) {
return reply(_boom2.default.clientTimeout(response.message));
}
if (response instanceof _elasticsearch2.default.errors.InternalServerError) {
return reply(_boom2.default.badImplementation(response.message));
}
if (response instanceof _elasticsearch2.default.errors.PreconditionFailed) {
return reply(_boom2.default.preconditionFailed(response.message));
}
if (response instanceof _elasticsearch2.default.errors.Conflict) {
return reply(_boom2.default.conflict(response.message));
}
if (response instanceof _elasticsearch2.default.errors.Forbidden) {
return reply(_boom2.default.forbidden(response.message));
}
if (response instanceof _elasticsearch2.default.errors.NotFound) {
return reply(_boom2.default.notFound(response.message));
}
if (response instanceof _elasticsearch2.default.errors.BadRequest) {
return reply(_boom2.default.badRequest(response.message));
}
if (response instanceof _elasticsearch2.default.errors.Generic) {
return reply(_boom2.default.badImplementation(response.message));
}
return reply.continue();
});
server.expose('es', es);
next();
};
register.attributes = {
pkg: _package2.default
};
exports.default = {
register: register
}; |
import { safeCallback } from "./callback";
import { load } from "./load";
import { hasEmptyStatus, hadStartedLoading, setStatus } from "./data";
import { cancelLoading } from "./cancelOnExit";
import { unobserveEntered } from "./unobserve";
import { statusEntered } from "./elementStatus";
import { addClass, removeClass } from "./class";
export const onEnter = (element, entry, settings, instance) => {
const dontLoad = hadStartedLoading(element); /* Save status
before setting it, to prevent loading it again. Fixes #526. */
setStatus(element, statusEntered);
addClass(element, settings.class_entered);
removeClass(element, settings.class_exited);
unobserveEntered(element, settings, instance);
safeCallback(settings.callback_enter, element, entry, instance);
if (dontLoad) return;
load(element, settings, instance);
};
export const onExit = (element, entry, settings, instance) => {
if (hasEmptyStatus(element)) return; //Ignore the first pass, at landing
addClass(element, settings.class_exited);
cancelLoading(element, entry, settings, instance);
safeCallback(settings.callback_exit, element, entry, instance);
};
|
'use strict';
module.exports = function (suite) {
suite.forEach(function (file) {
file.test = file.module;
});
return suite;
};
|
/**
* Express configuration
*/
'use strict';
var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
module.exports = function(app) {
var env = app.get('env');
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({
mongooseConnection: mongoose.connection,
db: 'phleep'
})
}));
if ('production' === env) {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', path.join(config.root, 'public'));
app.use(morgan('dev'));
}
if ('development' === env || 'test' === env) {
app.use(require('connect-livereload')());
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'client')));
app.set('appPath', path.join(config.root, 'client'));
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
}; |
Package.describe({
name: 'iron:router',
summary: 'Routing specifically designed for Meteor',
version: "1.0.5",
git: "https://github.com/eventedmind/iron-router"
});
Npm.depends({
'body-parser': '1.8.1'
});
Package.on_use(function (api) {
api.versionsFrom('METEOR@0.9.2');
// meteor dependencies
api.use('underscore');
api.use('webapp', 'server');
api.use('deps', 'client');
api.use('ui');
api.use('templating');
// for cloning
api.use('ejson');
// for dynamic scoping with environment variables
api.use('meteor')
// main namespace and utils
api.use('iron:core@1.0.4');
api.imply('iron:core');
// ui layout
api.use('iron:layout@1.0.5');
// connect like middleware stack for client/server
api.use('iron:middleware-stack@1.0.4');
// client and server side url utilities and compiling
api.use('iron:url@1.0.4');
// for reactive urls and pushState in the browser
api.use('iron:location@1.0.4');
// for RouteController which inherits from this
api.use('iron:controller@1.0.4');
api.add_files('lib/current_options.js');
api.add_files('lib/http_methods.js');
api.add_files('lib/route_controller.js');
api.add_files('lib/route_controller_server.js', 'server');
api.add_files('lib/route_controller_client.js', 'client');
api.add_files('lib/route.js');
api.add_files('lib/router.js');
api.add_files('lib/hooks.js');
api.add_files('lib/helpers.js');
api.add_files('lib/router_client.js', 'client');
api.add_files('lib/body_parser_server.js', 'server');
api.add_files('lib/router_server.js', 'server');
api.add_files('lib/plugins.js');
api.add_files('lib/global_router.js');
api.add_files('lib/templates.html');
// symbol exports
api.export('Router');
api.export('RouteController');
});
Package.on_test(function (api) {
api.use('iron:router');
api.use('tinytest');
api.use('test-helpers');
api.add_files('test/helpers.js');
api.add_files('test/route_test.js');
api.add_files('test/router_test.js');
api.add_files('test/route_controller_test.js');
});
|
'use strict';
var _systemImportTransformerGlobalIdentifier =
typeof window !== 'undefined'
? window
: typeof self !== 'undefined'
? self
: typeof global !== 'undefined'
? global
: {};
typeof _systemImportTransformerGlobalIdentifier.define === 'function' &&
_systemImportTransformerGlobalIdentifier.define.amd
? new Promise(function(resolve, reject) {
_systemImportTransformerGlobalIdentifier.require(
['npmModule'],
resolve,
reject,
);
})
: (typeof module !== 'undefined' &&
module.exports &&
typeof require !== 'undefined') ||
(typeof module !== 'undefined' &&
module.component &&
_systemImportTransformerGlobalIdentifier.require &&
_systemImportTransformerGlobalIdentifier.require.loader === 'component')
? Promise.resolve(require('npmModule'))
: Promise.resolve(_systemImportTransformerGlobalIdentifier['npmModule']);
typeof _systemImportTransformerGlobalIdentifier.define === 'function' &&
_systemImportTransformerGlobalIdentifier.define.amd
? new Promise(function(resolve, reject) {
_systemImportTransformerGlobalIdentifier.require(
['npmModule/subModule'],
resolve,
reject,
);
})
: (typeof module !== 'undefined' &&
module.exports &&
typeof require !== 'undefined') ||
(typeof module !== 'undefined' &&
module.component &&
_systemImportTransformerGlobalIdentifier.require &&
_systemImportTransformerGlobalIdentifier.require.loader === 'component')
? Promise.resolve(require('npmModule/subModule'))
: Promise.resolve(
_systemImportTransformerGlobalIdentifier['npmModule/subModule'],
);
typeof _systemImportTransformerGlobalIdentifier.define === 'function' &&
_systemImportTransformerGlobalIdentifier.define.amd
? new Promise(function(resolve, reject) {
_systemImportTransformerGlobalIdentifier.require(
['./myModule'],
resolve,
reject,
);
})
: (typeof module !== 'undefined' &&
module.exports &&
typeof require !== 'undefined') ||
(typeof module !== 'undefined' &&
module.component &&
_systemImportTransformerGlobalIdentifier.require &&
_systemImportTransformerGlobalIdentifier.require.loader === 'component')
? Promise.resolve(require('./myModule'))
: Promise.resolve(_systemImportTransformerGlobalIdentifier['./myModule']);
typeof _systemImportTransformerGlobalIdentifier.define === 'function' &&
_systemImportTransformerGlobalIdentifier.define.amd
? new Promise(function(resolve, reject) {
_systemImportTransformerGlobalIdentifier.require(
['../myOuterModule'],
resolve,
reject,
);
})
: (typeof module !== 'undefined' &&
module.exports &&
typeof require !== 'undefined') ||
(typeof module !== 'undefined' &&
module.component &&
_systemImportTransformerGlobalIdentifier.require &&
_systemImportTransformerGlobalIdentifier.require.loader === 'component')
? Promise.resolve(require('../myOuterModule'))
: Promise.resolve(
_systemImportTransformerGlobalIdentifier['../myOuterModule'],
);
typeof _systemImportTransformerGlobalIdentifier.define === 'function' &&
_systemImportTransformerGlobalIdentifier.define.amd
? new Promise(function(resolve, reject) {
_systemImportTransformerGlobalIdentifier.require(
['/myRootLevelModule'],
resolve,
reject,
);
})
: (typeof module !== 'undefined' &&
module.exports &&
typeof require !== 'undefined') ||
(typeof module !== 'undefined' &&
module.component &&
_systemImportTransformerGlobalIdentifier.require &&
_systemImportTransformerGlobalIdentifier.require.loader === 'component')
? Promise.resolve(require('/myRootLevelModule'))
: Promise.resolve(
_systemImportTransformerGlobalIdentifier['/myRootLevelModule'],
);
import('npmModule');
import('npmModule/subModule');
import('./myModule');
import('../myOuterModule');
import('/myRootLevelModule');
|
const fs = require('fs')
const path = require('path')
const express = require('express')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-renderer')
const { ERROR_NAME } = require('../src')
const isProd = process.env.NODE_ENV === 'production'
const app = express()
const template = fs.readFileSync(resolve('./index.template.html'), 'utf-8')
function createRenderer (bundle, options) {
return createBundleRenderer(bundle, Object.assign(options, {
template,
// recommended for performance
runInNewContext: false
}))
}
let renderer
let readyPromise
if (isProd) {
// In production: create server renderer using built server bundle.
// The server bundle is generated by vue-ssr-webpack-plugin.
const bundle = require('./dist/vue-ssr-server-bundle.json')
// The client manifests are optional, but it allows the renderer
// to automatically infer preload/prefetch links and directly add <script>
// tags for any async chunks used during render, avoiding waterfall requests.
const clientManifest = require('./dist/vue-ssr-client-manifest.json')
renderer = createRenderer(bundle, {
clientManifest
})
} else {
// In development: setup the dev server with watch and hot-reload,
// and create a new renderer on bundle / index template update.
readyPromise = require('./build/setup-dev-server')(app, (bundle, options) => {
renderer = createRenderer(bundle, options)
})
}
const serve = (path, cache) => express.static(resolve(path), {
maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0
})
app.use('/dist', serve('./dist', true))
app.use('/public', serve('./public', true))
app.use('/manifest.json', serve('./manifest.json', true))
function render (req, res) {
res.setHeader('Content-Type', 'text/html')
const handleError = (err) => {
const { name, status } = err || { status: 500 }
if (name === ERROR_NAME) {
const { type } = err
if (type === 'cancel') {
return res.redirect('back')
} else if (type === 'redirect') {
return res.redirect(status || 302, err.value)
}
}
res.status(status).end(`Error - ${status}`)
if (typeof status !== 'number' || status < 100 || status >= 500) {
console.error(`error during render : ${req.url}`)
console.error(err.stack)
}
}
const context = {
url: req.url
}
renderer.renderToString(context, (err, html) => {
if (err) {
return handleError(err)
}
res.status(context.status || 200).end(html)
})
}
app.get('*', isProd ? render : (req, res) => {
readyPromise.then(() => render(req, res))
})
const port = process.env.PORT || 8080
app.listen(port, () => {
console.log(`server started at localhost:${port}`)
})
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Requestresponse = mongoose.model('Requestresponse');
/**
* Globals
*/
var user, requestresponse;
/**
* Unit tests
*/
describe('Requestresponse Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
requestresponse = new Requestresponse({
name: 'Requestresponse Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return requestresponse.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
requestresponse.name = '';
return requestresponse.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Requestresponse.remove().exec();
User.remove().exec();
done();
});
}); |
/*
Source: git://github.com/visionmedia/node-querystring.git
*/
/**
* Object#toString() ref for stringify().
*/
var toString = Object.prototype.toString;
/**
* Object#hasOwnProperty ref
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* see issue #70
*/
var isRestorableProto = (function () {
var o;
if (!Object.create) return false;
o = Object.create(null);
o.__proto__ = Object.prototype;
return o.hasOwnProperty === hasOwnProperty;
})();
/**
* Array#indexOf shim.
*/
var indexOf = typeof Array.prototype.indexOf === 'function'
? function(arr, el) { return arr.indexOf(el); }
: function(arr, el) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === el) return i;
}
return -1;
};
/**
* Array.isArray shim.
*/
var isArray = Array.isArray || function(arr) {
return toString.call(arr) == '[object Array]';
};
/**
* Object.keys shim.
*/
var objectKeys = Object.keys || function(obj) {
var ret = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret.push(key);
}
}
return ret;
};
/**
* Array#forEach shim.
*/
var forEach = typeof Array.prototype.forEach === 'function'
? function(arr, fn) { return arr.forEach(fn); }
: function(arr, fn) {
for (var i = 0; i < arr.length; i++) fn(arr[i]);
};
/**
* Array#reduce shim.
*/
var reduce = function(arr, fn, initial) {
if (typeof arr.reduce === 'function') return arr.reduce(fn, initial);
var res = initial;
for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]);
return res;
};
/**
* Create a nullary object if possible
*/
function createObject() {
return isRestorableProto
? Object.create(null)
: {};
}
/**
* Cache non-integer test regexp.
*/
var isint = /^[0-9]+$/;
function promote(parent, key) {
if (parent[key].length == 0) return parent[key] = createObject();
var t = createObject();
for (var i in parent[key]) {
if (hasOwnProperty.call(parent[key], i)) {
t[i] = parent[key][i];
}
}
parent[key] = t;
return t;
}
function parse(parts, parent, key, val) {
var part = parts.shift();
// end
if (!part) {
if (isArray(parent[key])) {
parent[key].push(val);
} else if ('object' == typeof parent[key]) {
parent[key] = val;
} else if ('undefined' == typeof parent[key]) {
parent[key] = val;
} else {
parent[key] = [parent[key], val];
}
// array
} else {
var obj = parent[key] = parent[key] || [];
if (']' == part) {
if (isArray(obj)) {
if ('' != val) obj.push(val);
} else if ('object' == typeof obj) {
obj[objectKeys(obj).length] = val;
} else {
obj = parent[key] = [parent[key], val];
}
// prop
} else if (~indexOf(part, ']')) {
part = part.substr(0, part.length - 1);
if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
parse(parts, obj, part, val);
// key
} else {
if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
parse(parts, obj, part, val);
}
}
}
/**
* Merge parent key/val pair.
*/
function merge(parent, key, val){
if (~indexOf(key, ']')) {
var parts = key.split('[')
, len = parts.length
, last = len - 1;
parse(parts, parent, 'base', val);
// optimize
} else {
if (!isint.test(key) && isArray(parent.base)) {
var t = createObject();
for (var k in parent.base) t[k] = parent.base[k];
parent.base = t;
}
set(parent.base, key, val);
}
return parent;
}
/**
* Compact sparse arrays.
*/
function compact(obj) {
if ('object' != typeof obj) return obj;
if (isArray(obj)) {
var ret = [];
for (var i in obj) {
if (hasOwnProperty.call(obj, i)) {
ret.push(obj[i]);
}
}
return ret;
}
for (var key in obj) {
obj[key] = compact(obj[key]);
}
return obj;
}
/**
* Restore Object.prototype.
* see pull-request #58
*/
function restoreProto(obj) {
if (!isRestorableProto) return obj;
if (isArray(obj)) return obj;
if (obj && 'object' != typeof obj) return obj;
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
obj[key] = restoreProto(obj[key]);
}
}
obj.__proto__ = Object.prototype;
return obj;
}
/**
* Parse the given obj.
*/
function parseObject(obj){
var ret = { base: {} };
forEach(objectKeys(obj), function(name){
merge(ret, name, obj[name]);
});
return compact(ret.base);
}
/**
* Parse the given str.
*/
function parseString(str){
var ret = reduce(String(str).split('&'), function(ret, pair){
var eql = indexOf(pair, '=')
, brace = lastBraceInKey(pair)
, key = pair.substr(0, brace || eql)
, val = pair.substr(brace || eql, pair.length)
, val = val.substr(indexOf(val, '=') + 1, val.length);
// ?foo
if ('' == key) key = pair, val = '';
if ('' == key) return ret;
return merge(ret, decode(key), decode(val));
}, { base: createObject() }).base;
return restoreProto(compact(ret));
}
/**
* Parse the given query `str` or `obj`, returning an object.
*
* @param {String} str | {Object} obj
* @return {Object}
* @api public
*/
exports.parse = function(str){
if (null == str || '' == str) return {};
return 'object' == typeof str
? parseObject(str)
: parseString(str);
};
/**
* Turn the given `obj` into a query string
*
* @param {Object} obj
* @return {String}
* @api public
*/
var stringify = exports.stringify = function(obj, prefix) {
if (isArray(obj)) {
return stringifyArray(obj, prefix);
} else if ('[object Object]' == toString.call(obj)) {
return stringifyObject(obj, prefix);
} else if ('string' == typeof obj) {
return stringifyString(obj, prefix);
} else {
return prefix + '=' + encodeURIComponent(String(obj));
}
};
/**
* Stringify the given `str`.
*
* @param {String} str
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyString(str, prefix) {
if (!prefix) throw new TypeError('stringify expects an object');
return prefix + '=' + encodeURIComponent(str);
}
/**
* Stringify the given `arr`.
*
* @param {Array} arr
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyArray(arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
}
return ret.join('&');
}
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @param {String} prefix
* @return {String}
* @api private
*/
function stringifyObject(obj, prefix) {
var ret = []
, keys = objectKeys(obj)
, key;
for (var i = 0, len = keys.length; i < len; ++i) {
key = keys[i];
if ('' == key) continue;
if (null == obj[key]) {
ret.push(encodeURIComponent(key) + '=');
} else {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
}
}
return ret.join('&');
}
/**
* Set `obj`'s `key` to `val` respecting
* the weird and wonderful syntax of a qs,
* where "foo=bar&foo=baz" becomes an array.
*
* @param {Object} obj
* @param {String} key
* @param {String} val
* @api private
*/
function set(obj, key, val) {
var v = obj[key];
if (undefined === v) {
obj[key] = val;
} else if (isArray(v)) {
v.push(val);
} else {
obj[key] = [v, val];
}
}
/**
* Locate last brace in `str` within the key.
*
* @param {String} str
* @return {Number}
* @api private
*/
function lastBraceInKey(str) {
var len = str.length
, brace
, c;
for (var i = 0; i < len; ++i) {
c = str[i];
if (']' == c) brace = false;
if ('[' == c) brace = true;
if ('=' == c && !brace) return i;
}
}
/**
* Decode `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
function decode(str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (err) {
return str;
}
}
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'sr-latn', {
clear: 'Clear', // MISSING
highlight: 'Highlight', // MISSING
options: 'Color Options', // MISSING
selected: 'Selected Color', // MISSING
title: 'Select color' // MISSING
} );
|
const assert = require('assert');
const { checkConfigValid } = require('../../../lib/common/utils/checkConfigValid');
describe('checkConfigValid()', () => {
describe('endpoint', () => {
it('should success when endpoint is valid', () => {
try {
const endpoint = 'testa_-.com';
checkConfigValid(endpoint, 'endpoint');
assert(true);
} catch (error) {
assert(false);
}
});
it('should throw when endpoint includes invalid character', () => {
const errorStr = '中~!@#$%^&*()+={}[]|\\";\',<>?';
errorStr.split('').map(_ => `test-a_b.${_}.com`).forEach(
str => {
try {
checkConfigValid(str, 'endpoint');
assert(false);
} catch (error) {
assert(error.message.includes('endpoint'));
}
}
);
});
});
describe('region', () => {
it('should success when region is valid', () => {
try {
const region = 'oss-cn-hangzhou';
checkConfigValid(region, 'region');
assert(true);
} catch (error) {
assert(false);
}
});
it('should throw when region includes invalid character', () => {
const errorStr = '中~!@#$%^&*()+={}[]|\\";\',<>?';
errorStr.split('').map(_ => `oss-${_}hangzhou`).forEach(
str => {
try {
checkConfigValid(str, 'region');
assert(false);
} catch (error) {
assert(error.message.includes('region'));
}
}
);
});
});
});
|
export default {
getNotices(req, res) {
res.json([{
id: '000000001',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
title: '你收到了 14 份新周报',
datetime: '2017-08-09',
type: '通知',
}, {
id: '000000002',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
title: '你推荐的 曲妮妮 已通过第三轮面试',
datetime: '2017-08-08',
type: '通知',
}, {
id: '000000003',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/kISTdvpyTAhtGxpovNWd.png',
title: '这种模板可以区分多种通知类型',
datetime: '2017-08-07',
read: true,
type: '通知',
}, {
id: '000000004',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/GvqBnKhFgObvnSGkDsje.png',
title: '左侧图标用于区分不同的类型',
datetime: '2017-08-07',
type: '通知',
}, {
id: '000000005',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
title: '内容不要超过两行字,超出时自动截断',
datetime: '2017-08-07',
type: '通知',
}, {
id: '000000006',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '曲丽丽 评论了你',
description: '描述信息描述信息描述信息',
datetime: '2017-08-07',
type: '消息',
}, {
id: '000000007',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '朱偏右 回复了你',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: '消息',
}, {
id: '000000008',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '标题',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: '消息',
}, {
id: '000000009',
title: '任务名称',
description: '任务需要在 2017-01-12 20:00 前启动',
extra: '未开始',
status: 'todo',
type: '待办',
}, {
id: '000000010',
title: '第三方紧急代码变更',
description: '冠霖提交于 2017-01-06,需在 2017-01-07 前完成代码变更任务',
extra: '马上到期',
status: 'urgent',
type: '待办',
}, {
id: '000000011',
title: '信息安全考试',
description: '指派竹尔于 2017-01-09 前完成更新并发布',
extra: '已耗时 8 天',
status: 'doing',
type: '待办',
}, {
id: '000000012',
title: 'ABCD 版本发布',
description: '冠霖提交于 2017-01-06,需在 2017-01-07 前完成代码变更任务',
extra: '进行中',
status: 'processing',
type: '待办',
}])
},
}
|
"use strict";
//// Typen fuer Klassen
exports.__esModule = true;
function assertNever(x) {
throw new Error("Unexpected object: " + x);
}
exports.assertNever = assertNever;
// #region FAHRPREIS_T
// Fahrpreise hinter ZeitZeile
var FAHRPREIS_T;
(function (FAHRPREIS_T) {
FAHRPREIS_T["KEINE_ANGABE"] = "FAHRPREIS_KEINE_ANGABE";
FAHRPREIS_T["EINFACH"] = "FAHRPREIS_EINFACH";
FAHRPREIS_T["EINFACH_UND_RUECK"] = "FAHRPREIS_EINFACH_UND_RUECK";
FAHRPREIS_T["AB"] = "FAHRPREIS_AB";
})(FAHRPREIS_T = exports.FAHRPREIS_T || (exports.FAHRPREIS_T = {}));
// #endregion
|
export default {
Order: '订单',
Picture: '图片',
Address: '地址',
Price: '价格',
Discount: '打折',
Quantity: '数量',
'Order Item': '订单商品',
'Order Items': '订单商品',
'Order Log': '订单日志',
Payed: '已支付',
State: '状态',
'Failure Reason': '失败原因',
'Expire At': '过期日期',
Order_New: '新订单',
Order_Payed: '已支付',
Order_Confirmed: '审核通过',
Order_Shipped: '已发货',
Order_Done: '完成',
Order_Refund: '退款中',
Order_Failed: '失败',
Goods: '商品',
'Can not create any order': '未能创建任何订单',
Shipping: '运费',
'Total Amount': '总金额',
'Pay Amount': '支付金额',
'Payed Amount': '已支付',
'Refund Amount': '退款金额',
'Refunded Amount': '已经退金额',
Shipped: '已发货',
'Payment Timeout': '支付超时',
'Receive Timeout': '收货超时',
'Refund Timeout': '退款超时',
Second: '秒',
Payment: '支付方式',
'SKU Desc': 'SKU描述',
'Order created': '订单创建',
'Modified shipping fee': '修改运费',
'Modified total price': '修改总价',
'Order confirmed': '确认',
'Order rejected': '拒绝',
'Order payed': '付款',
'Order received': '确认收货',
'Apply refund': '申请退款',
'Order refunded': '订单退款',
'Refund rejected': '拒绝退款',
'Order shipped': '已发货',
Confirm: '确认',
Ship: '发货',
'Refund Reason': '退款原因',
'Do you confirm the order?': '确定要删除订单吗?'
};
|
/**
* 简易消息提示框组件
* @module Toast
* @author liweitao
*/
PP.define('toast', function (require) {
// 调用遮罩层组件
var Overlay = require('overlay');
// 实例,单例模式
var instance = null;
/**
* @class Toast
* @classdesc 提示框类,单例
* @alias module:Toast
*/
var Toast = _.Class.extend({
/**
* toast.
* @constructor
* @param {Object|String} options
* @param {String|HTMLElement|Zepto} [options.content] - 提示信息内容
* @param {Number} [options.duration] - 提示持续时间
*/
construct: function (options) {
if (typeof options === 'string') {
options = {
content: options
};
}
this.conf = $.extend({
content: '',
duration: 3000
}, options);
// 单例
if (instance) {
instance.setTimer.call(instance);
instance.content(this.conf.content);
instance.show();
return instance;
}
this.$dom = $('<div class="toast"></div>');
this.content(this.conf.content);
this.setTimer();
this.overlay = new Overlay({
content: this.$dom,
mask: false,
modal: false
});
this.show();
instance = this;
return instance;
},
/*
* @description 设置定时器
*/
setTimer: function () {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout($.proxy(function () {
this.hide();
}, this), this.conf.duration);
},
/**
* @description 展示提示信息框
* @return {Object} this - 实例本身,方便链式调用
*/
show: function () {
this.overlay.show();
return this;
},
/**
* @description 隐藏提示信息框
* @return {Object} this - 实例本身,方便链式调用
*/
hide: function () {
this.overlay.hide();
return this;
},
/**
* @description 获取/填充内容
* @param {String|HTMLElement|Zepto} [content] - 当conten为空时是获取,否则是填充内容
*/
content: function (content) {
if (content === undefined) {
return this.$dom.html();
} else {
this.$dom.html(content);
}
}
});
return Toast;
});
|
/*
Highcharts JS v9.0.1 (2021-02-15)
Exporting module
(c) 2010-2021 Torstein Honsi
License: www.highcharts.com/license
*/
(function(c){"object"===typeof module&&module.exports?(c["default"]=c,module.exports=c):"function"===typeof define&&define.amd?define("highcharts/modules/exporting",["highcharts"],function(p){c(p);c.Highcharts=p;return c}):c("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(c){function p(c,k,h,n){c.hasOwnProperty(k)||(c[k]=n.apply(null,h))}c=c?c._modules:{};p(c,"Extensions/FullScreen.js",[c["Core/Chart/Chart.js"],c["Core/Globals.js"],c["Core/Renderer/HTML/AST.js"],c["Core/Utilities.js"]],
function(c,k,h,n){var l=n.addEvent;n=function(){function c(e){this.chart=e;this.isOpen=!1;e=e.renderTo;this.browserProps||("function"===typeof e.requestFullscreen?this.browserProps={fullscreenChange:"fullscreenchange",requestFullscreen:"requestFullscreen",exitFullscreen:"exitFullscreen"}:e.mozRequestFullScreen?this.browserProps={fullscreenChange:"mozfullscreenchange",requestFullscreen:"mozRequestFullScreen",exitFullscreen:"mozCancelFullScreen"}:e.webkitRequestFullScreen?this.browserProps={fullscreenChange:"webkitfullscreenchange",
requestFullscreen:"webkitRequestFullScreen",exitFullscreen:"webkitExitFullscreen"}:e.msRequestFullscreen&&(this.browserProps={fullscreenChange:"MSFullscreenChange",requestFullscreen:"msRequestFullscreen",exitFullscreen:"msExitFullscreen"}))}c.prototype.close=function(){var e=this.chart,c=e.options.chart;if(this.isOpen&&this.browserProps&&e.container.ownerDocument instanceof Document)e.container.ownerDocument[this.browserProps.exitFullscreen]();this.unbindFullscreenEvent&&this.unbindFullscreenEvent();
e.setSize(this.origWidth,this.origHeight,!1);this.origHeight=this.origWidth=void 0;c&&(c.width=this.origWidthOption,c.height=this.origHeightOption);this.origHeightOption=this.origWidthOption=void 0;this.isOpen=!1;this.setButtonText()};c.prototype.open=function(){var e=this,c=e.chart,h=c.options.chart;h&&(e.origWidthOption=h.width,e.origHeightOption=h.height);e.origWidth=c.chartWidth;e.origHeight=c.chartHeight;if(e.browserProps){e.unbindFullscreenEvent=l(c.container.ownerDocument,e.browserProps.fullscreenChange,
function(){e.isOpen?(e.isOpen=!1,e.close()):(c.setSize(null,null,!1),e.isOpen=!0,e.setButtonText())});if(h=c.renderTo[e.browserProps.requestFullscreen]())h["catch"](function(){alert("Full screen is not supported inside a frame.")});l(c,"destroy",e.unbindFullscreenEvent)}};c.prototype.setButtonText=function(){var e,c=this.chart,n=c.exportDivElements,k=c.options.exporting,l=null===(e=null===k||void 0===k?void 0:k.buttons)||void 0===e?void 0:e.contextButton.menuItems;e=c.options.lang;(null===k||void 0===
k?0:k.menuItemDefinitions)&&(null===e||void 0===e?0:e.exitFullscreen)&&e.viewFullscreen&&l&&n&&n.length&&h.setElementHTML(n[l.indexOf("viewFullscreen")],this.isOpen?e.exitFullscreen:k.menuItemDefinitions.viewFullscreen.text||e.viewFullscreen)};c.prototype.toggle=function(){this.isOpen?this.close():this.open()};return c}();k.Fullscreen=n;l(c,"beforeRender",function(){this.fullscreen=new k.Fullscreen(this)});return k.Fullscreen});p(c,"Mixins/Navigation.js",[],function(){return{initUpdate:function(c){c.navigation||
(c.navigation={updates:[],update:function(c,h){this.updates.forEach(function(k){k.update.call(k.context,c,h)})}})},addUpdate:function(c,k){k.navigation||this.initUpdate(k);k.navigation.updates.push({update:c,context:k})}}});p(c,"Extensions/Exporting.js",[c["Core/Chart/Chart.js"],c["Mixins/Navigation.js"],c["Core/Globals.js"],c["Core/Options.js"],c["Core/Color/Palette.js"],c["Core/Renderer/SVG/SVGRenderer.js"],c["Core/Utilities.js"]],function(c,k,h,n,l,p,e){var z=h.doc,G=h.isTouchDevice,B=h.win;n=
n.defaultOptions;var x=e.addEvent,u=e.css,y=e.createElement,E=e.discardElement,A=e.extend,H=e.find,D=e.fireEvent,I=e.isObject,v=e.merge,F=e.objectEach,q=e.pick,J=e.removeEvent,K=e.uniqueKey;A(n.lang,{viewFullscreen:"View in full screen",exitFullscreen:"Exit from full screen",printChart:"Print chart",downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image",contextButtonTitle:"Chart context menu"});n.navigation||
(n.navigation={});v(!0,n.navigation,{buttonOptions:{theme:{},symbolSize:14,symbolX:12.5,symbolY:10.5,align:"right",buttonSpacing:3,height:22,verticalAlign:"top",width:24}});v(!0,n.navigation,{menuStyle:{border:"1px solid "+l.neutralColor40,background:l.backgroundColor,padding:"5px 0"},menuItemStyle:{padding:"0.5em 1em",color:l.neutralColor80,background:"none",fontSize:G?"14px":"11px",transition:"background 250ms, color 250ms"},menuItemHoverStyle:{background:l.highlightColor80,color:l.backgroundColor},
buttonOptions:{symbolFill:l.neutralColor60,symbolStroke:l.neutralColor60,symbolStrokeWidth:3,theme:{padding:5}}});n.exporting={type:"image/png",url:"https://export.highcharts.com/",printMaxWidth:780,scale:2,buttons:{contextButton:{className:"highcharts-contextbutton",menuClassName:"highcharts-contextmenu",symbol:"menu",titleKey:"contextButtonTitle",menuItems:"viewFullscreen printChart separator downloadPNG downloadJPEG downloadPDF downloadSVG".split(" ")}},menuItemDefinitions:{viewFullscreen:{textKey:"viewFullscreen",
onclick:function(){this.fullscreen.toggle()}},printChart:{textKey:"printChart",onclick:function(){this.print()}},separator:{separator:!0},downloadPNG:{textKey:"downloadPNG",onclick:function(){this.exportChart()}},downloadJPEG:{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}},downloadPDF:{textKey:"downloadPDF",onclick:function(){this.exportChart({type:"application/pdf"})}},downloadSVG:{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}}};
h.post=function(a,b,f){var d=y("form",v({method:"post",action:a,enctype:"multipart/form-data"},f),{display:"none"},z.body);F(b,function(a,b){y("input",{type:"hidden",name:b,value:a},null,d)});d.submit();E(d)};h.isSafari&&h.win.matchMedia("print").addListener(function(a){h.printingChart&&(a.matches?h.printingChart.beforePrint():h.printingChart.afterPrint())});A(c.prototype,{sanitizeSVG:function(a,b){var f=a.indexOf("</svg>")+6,d=a.substr(f);a=a.substr(0,f);b&&b.exporting&&b.exporting.allowHTML&&d&&
(d='<foreignObject x="0" y="0" width="'+b.chart.width+'" height="'+b.chart.height+'"><body xmlns="http://www.w3.org/1999/xhtml">'+d.replace(/(<(?:img|br).*?(?=>))>/g,"$1 />")+"</body></foreignObject>",a=a.replace("</svg>",d+"</svg>"));a=a.replace(/zIndex="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/url\(("|")(.*?)("|");?\)/g,"url($2)").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ (|NS[0-9]+:)href=/g,
" xlink:href=").replace(/\n/," ").replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g,'$1="rgb($2)" $1-opacity="$3"').replace(/ /g,"\u00a0").replace(/­/g,"\u00ad");this.ieSanitizeSVG&&(a=this.ieSanitizeSVG(a));return a},getChartHTML:function(){this.styledMode&&this.inlineStyles();return this.container.innerHTML},getSVG:function(a){var b,f=v(this.options,a);f.plotOptions=v(this.userOptions.plotOptions,a&&a.plotOptions);f.time=v(this.userOptions.time,a&&a.time);var d=y("div",
null,{position:"absolute",top:"-9999em",width:this.chartWidth+"px",height:this.chartHeight+"px"},z.body);var e=this.renderTo.style.width;var r=this.renderTo.style.height;e=f.exporting.sourceWidth||f.chart.width||/px$/.test(e)&&parseInt(e,10)||(f.isGantt?800:600);r=f.exporting.sourceHeight||f.chart.height||/px$/.test(r)&&parseInt(r,10)||400;A(f.chart,{animation:!1,renderTo:d,forExport:!0,renderer:"SVGRenderer",width:e,height:r});f.exporting.enabled=!1;delete f.data;f.series=[];this.series.forEach(function(a){b=
v(a.userOptions,{animation:!1,enableMouseTracking:!1,showCheckbox:!1,visible:a.visible});b.isInternal||f.series.push(b)});this.axes.forEach(function(a){a.userOptions.internalKey||(a.userOptions.internalKey=K())});var h=new c(f,this.callback);a&&["xAxis","yAxis","series"].forEach(function(b){var d={};a[b]&&(d[b]=a[b],h.update(d))});this.axes.forEach(function(a){var b=H(h.axes,function(b){return b.options.internalKey===a.userOptions.internalKey}),d=a.getExtremes(),f=d.userMin;d=d.userMax;b&&("undefined"!==
typeof f&&f!==b.min||"undefined"!==typeof d&&d!==b.max)&&b.setExtremes(f,d,!0,!1)});e=h.getChartHTML();D(this,"getSVG",{chartCopy:h});e=this.sanitizeSVG(e,f);f=null;h.destroy();E(d);return e},getSVGForExport:function(a,b){var f=this.options.exporting;return this.getSVG(v({chart:{borderRadius:0}},f.chartOptions,b,{exporting:{sourceWidth:a&&a.sourceWidth||f.sourceWidth,sourceHeight:a&&a.sourceHeight||f.sourceHeight}}))},getFilename:function(){var a=this.userOptions.title&&this.userOptions.title.text,
b=this.options.exporting.filename;if(b)return b.replace(/\//g,"-");"string"===typeof a&&(b=a.toLowerCase().replace(/<\/?[^>]+(>|$)/g,"").replace(/[\s_]+/g,"-").replace(/[^a-z0-9\-]/g,"").replace(/^[\-]+/g,"").replace(/[\-]+/g,"-").substr(0,24).replace(/[\-]+$/g,""));if(!b||5>b.length)b="chart";return b},exportChart:function(a,b){b=this.getSVGForExport(a,b);a=v(this.options.exporting,a);h.post(a.url,{filename:a.filename?a.filename.replace(/\//g,"-"):this.getFilename(),type:a.type,width:a.width||0,
scale:a.scale,svg:b},a.formAttributes)},moveContainers:function(a){(this.fixedDiv?[this.fixedDiv,this.scrollingContainer]:[this.container]).forEach(function(b){a.appendChild(b)})},beforePrint:function(){var a=z.body,b=this.options.exporting.printMaxWidth,f={childNodes:a.childNodes,origDisplay:[],resetParams:void 0};this.isPrinting=!0;this.pointer.reset(null,0);D(this,"beforePrint");b&&this.chartWidth>b&&(f.resetParams=[this.options.chart.width,void 0,!1],this.setSize(b,void 0,!1));[].forEach.call(f.childNodes,
function(a,b){1===a.nodeType&&(f.origDisplay[b]=a.style.display,a.style.display="none")});this.moveContainers(a);this.printReverseInfo=f},afterPrint:function(){if(this.printReverseInfo){var a=this.printReverseInfo.childNodes,b=this.printReverseInfo.origDisplay,f=this.printReverseInfo.resetParams;this.moveContainers(this.renderTo);[].forEach.call(a,function(a,f){1===a.nodeType&&(a.style.display=b[f]||"")});this.isPrinting=!1;f&&this.setSize.apply(this,f);delete this.printReverseInfo;delete h.printingChart;
D(this,"afterPrint")}},print:function(){var a=this;a.isPrinting||(h.printingChart=a,h.isSafari||a.beforePrint(),setTimeout(function(){B.focus();B.print();h.isSafari||setTimeout(function(){a.afterPrint()},1E3)},1))},contextMenu:function(a,b,f,d,c,h,k){var g=this,r=g.options.navigation,n=g.chartWidth,C=g.chartHeight,t="cache-"+a,m=g[t],w=Math.max(c,h);if(!m){g.exportContextMenu=g[t]=m=y("div",{className:a},{position:"absolute",zIndex:1E3,padding:w+"px",pointerEvents:"auto"},g.fixedDiv||g.container);
var l=y("ul",{className:"highcharts-menu"},{listStyle:"none",margin:0,padding:0},m);g.styledMode||u(l,A({MozBoxShadow:"3px 3px 10px #888",WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},r.menuStyle));m.hideMenu=function(){u(m,{display:"none"});k&&k.setState(0);g.openMenu=!1;u(g.renderTo,{overflow:"hidden"});e.clearTimeout(m.hideTimer);D(g,"exportMenuHidden")};g.exportEvents.push(x(m,"mouseleave",function(){m.hideTimer=B.setTimeout(m.hideMenu,500)}),x(m,"mouseenter",function(){e.clearTimeout(m.hideTimer)}),
x(z,"mouseup",function(b){g.pointer.inClass(b.target,a)||m.hideMenu()}),x(m,"click",function(){g.openMenu&&m.hideMenu()}));b.forEach(function(a){"string"===typeof a&&(a=g.options.exporting.menuItemDefinitions[a]);if(I(a,!0)){if(a.separator)var b=y("hr",null,null,l);else"viewData"===a.textKey&&g.isDataTableVisible&&(a.textKey="hideData"),b=y("li",{className:"highcharts-menu-item",onclick:function(b){b&&b.stopPropagation();m.hideMenu();a.onclick&&a.onclick.apply(g,arguments)}},null,l),b.appendChild(z.createTextNode(a.text||
g.options.lang[a.textKey])),g.styledMode||(b.onmouseover=function(){u(this,r.menuItemHoverStyle)},b.onmouseout=function(){u(this,r.menuItemStyle)},u(b,A({cursor:"pointer"},r.menuItemStyle)));g.exportDivElements.push(b)}});g.exportDivElements.push(l,m);g.exportMenuWidth=m.offsetWidth;g.exportMenuHeight=m.offsetHeight}b={display:"block"};f+g.exportMenuWidth>n?b.right=n-f-c-w+"px":b.left=f-w+"px";d+h+g.exportMenuHeight>C&&"top"!==k.alignOptions.verticalAlign?b.bottom=C-d-w+"px":b.top=d+h-w+"px";u(m,
b);u(g.renderTo,{overflow:""});g.openMenu=!0;D(g,"exportMenuShown")},addButton:function(a){var b=this,f=b.renderer,d=v(b.options.navigation.buttonOptions,a),c=d.onclick,e=d.menuItems,h=d.symbolSize||12;b.btnCount||(b.btnCount=0);b.exportDivElements||(b.exportDivElements=[],b.exportSVGElements=[]);if(!1!==d.enabled){var g=d.theme,k=g.states,n=k&&k.hover;k=k&&k.select;var C;b.styledMode||(g.fill=q(g.fill,l.backgroundColor),g.stroke=q(g.stroke,"none"));delete g.states;c?C=function(a){a&&a.stopPropagation();
c.call(b,a)}:e&&(C=function(a){a&&a.stopPropagation();b.contextMenu(t.menuClassName,e,t.translateX,t.translateY,t.width,t.height,t);t.setState(2)});d.text&&d.symbol?g.paddingLeft=q(g.paddingLeft,30):d.text||A(g,{width:d.width,height:d.height,padding:0});b.styledMode||(g["stroke-linecap"]="round",g.fill=q(g.fill,l.backgroundColor),g.stroke=q(g.stroke,"none"));var t=f.button(d.text,0,0,C,g,n,k).addClass(a.className).attr({title:q(b.options.lang[d._titleKey||d.titleKey],"")});t.menuClassName=a.menuClassName||
"highcharts-menu-"+b.btnCount++;if(d.symbol){var m=f.symbol(d.symbol,d.symbolX-h/2,d.symbolY-h/2,h,h,{width:h,height:h}).addClass("highcharts-button-symbol").attr({zIndex:1}).add(t);b.styledMode||m.attr({stroke:d.symbolStroke,fill:d.symbolFill,"stroke-width":d.symbolStrokeWidth||1})}t.add(b.exportingGroup).align(A(d,{width:t.width,x:q(d.x,b.buttonOffset)}),!0,"spacingBox");b.buttonOffset+=(t.width+d.buttonSpacing)*("right"===d.align?-1:1);b.exportSVGElements.push(t,m)}},destroyExport:function(a){var b=
a?a.target:this;a=b.exportSVGElements;var f=b.exportDivElements,d=b.exportEvents,c;a&&(a.forEach(function(a,d){a&&(a.onclick=a.ontouchstart=null,c="cache-"+a.menuClassName,b[c]&&delete b[c],b.exportSVGElements[d]=a.destroy())}),a.length=0);b.exportingGroup&&(b.exportingGroup.destroy(),delete b.exportingGroup);f&&(f.forEach(function(a,d){e.clearTimeout(a.hideTimer);J(a,"mouseleave");b.exportDivElements[d]=a.onmouseout=a.onmouseover=a.ontouchstart=a.onclick=null;E(a)}),f.length=0);d&&(d.forEach(function(a){a()}),
d.length=0)}});p.prototype.inlineToAttributes="fill stroke strokeLinecap strokeLinejoin strokeWidth textAnchor x y".split(" ");p.prototype.inlineBlacklist=[/-/,/^(clipPath|cssText|d|height|width)$/,/^font$/,/[lL]ogical(Width|Height)$/,/perspective/,/TapHighlightColor/,/^transition/,/^length$/];p.prototype.unstyledElements=["clipPath","defs","desc"];c.prototype.inlineStyles=function(){function a(a){return a.replace(/([A-Z])/g,function(a,b){return"-"+b.toLowerCase()})}function b(c){function f(b,f){w=
u=!1;if(k){for(q=k.length;q--&&!u;)u=k[q].test(f);w=!u}"transform"===f&&"none"===b&&(w=!0);for(q=e.length;q--&&!w;)w=e[q].test(f)||"function"===typeof b;w||z[f]===b&&"svg"!==c.nodeName||g[c.nodeName][f]===b||(d&&-1===d.indexOf(f)?m+=a(f)+":"+b+";":b&&c.setAttribute(a(f),b))}var m="",w,u,q;if(1===c.nodeType&&-1===n.indexOf(c.nodeName)){var r=B.getComputedStyle(c,null);var z="svg"===c.nodeName?{}:B.getComputedStyle(c.parentNode,null);if(!g[c.nodeName]){l=p.getElementsByTagName("svg")[0];var x=p.createElementNS(c.namespaceURI,
c.nodeName);l.appendChild(x);g[c.nodeName]=v(B.getComputedStyle(x,null));"text"===c.nodeName&&delete g.text.fill;l.removeChild(x)}if(h.isFirefox||h.isMS)for(var y in r)f(r[y],y);else F(r,f);m&&(r=c.getAttribute("style"),c.setAttribute("style",(r?r+";":"")+m));"svg"===c.nodeName&&c.setAttribute("stroke-width","1px");"text"!==c.nodeName&&[].forEach.call(c.children||c.childNodes,b)}}var c=this.renderer,d=c.inlineToAttributes,e=c.inlineBlacklist,k=c.inlineWhitelist,n=c.unstyledElements,g={},l;c=z.createElement("iframe");
u(c,{width:"1px",height:"1px",visibility:"hidden"});z.body.appendChild(c);var p=c.contentWindow.document;p.open();p.write('<svg xmlns="http://www.w3.org/2000/svg"></svg>');p.close();b(this.container.querySelector("svg"));l.parentNode.removeChild(l);c.parentNode.removeChild(c)};h.Renderer.prototype.symbols.menu=function(a,b,c,d){return[["M",a,b+2.5],["L",a+c,b+2.5],["M",a,b+d/2+.5],["L",a+c,b+d/2+.5],["M",a,b+d-1.5],["L",a+c,b+d-1.5]]};h.Renderer.prototype.symbols.menuball=function(a,b,c,d){a=[];d=
d/3-2;return a=a.concat(this.circle(c-d,b,d,d),this.circle(c-d,b+d+4,d,d),this.circle(c-d,b+2*(d+4),d,d))};c.prototype.renderExporting=function(){var a=this,b=a.options.exporting,c=b.buttons,d=a.isDirtyExporting||!a.exportSVGElements;a.buttonOffset=0;a.isDirtyExporting&&a.destroyExport();d&&!1!==b.enabled&&(a.exportEvents=[],a.exportingGroup=a.exportingGroup||a.renderer.g("exporting-group").attr({zIndex:3}).add(),F(c,function(b){a.addButton(b)}),a.isDirtyExporting=!1)};x(c,"init",function(){var a=
this;a.exporting={update:function(b,c){a.isDirtyExporting=!0;v(!0,a.options.exporting,b);q(c,!0)&&a.redraw()}};k.addUpdate(function(b,c){a.isDirtyExporting=!0;v(!0,a.options.navigation,b);q(c,!0)&&a.redraw()},a)});c.prototype.callbacks.push(function(a){a.renderExporting();x(a,"redraw",a.renderExporting);x(a,"destroy",a.destroyExport)})});p(c,"masters/modules/exporting.src.js",[],function(){})});
//# sourceMappingURL=exporting.js.map |
/**
* Copyright (c) 2014,Egret-Labs.org
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Egret-Labs.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var egret;
(function (egret) {
/**
* @class egret.TextField
* @classdesc
* TextField是egret的文本渲染类,采用浏览器/设备的API进行渲染,在不同的浏览器/设备中由于字体渲染方式不一,可能会有渲染差异
* 如果开发者希望所有平台完全无差异,请使用BitmapText
* @extends egret.DisplayObject
*/
var TextField = (function (_super) {
__extends(TextField, _super);
function TextField() {
_super.call(this);
this._inputEnabled = false;
/**
* 文本字段的类型。
* 以下 TextFieldType 常量中的任一个:TextFieldType.DYNAMIC(指定用户无法编辑的动态文本字段),或 TextFieldType.INPUT(指定用户可以编辑的输入文本字段)。
* 默认值为 dynamic。
* @member {string} egret.TextField#type
*/
this._type = "";
/**
* 作为文本字段中当前文本的字符串
* @member {string} egret.TextField#text
*/
this._text = "";
/**
* 指定文本字段是否是密码文本字段。
* 如果此属性的值为 true,则文本字段被视为密码文本字段,并使用星号而不是实际字符来隐藏输入的字符。如果为 false,则不会将文本字段视为密码文本字段。
* 默认值为 false。
* @member {boolean} egret.TextInput#displayAsPassword
*/
this._displayAsPassword = false;
/**
* 使用此文本格式的文本的字体名称,以字符串形式表示。
* 默认值 Arial。
* @member {any} egret.TextField#fontFamily
*/
this._fontFamily = TextField.default_fontFamily;
/**
* 使用此文本格式的文本的大小(以像素为单位)。
* 默认值为 30。
* @member {number} egret.TextField#size
*/
this._size = 30;
this._textColorString = "#FFFFFF";
/**
* 表示文本的颜色。
* 包含三个 8 位 RGB 颜色成分的数字;例如,0xFF0000 为红色,0x00FF00 为绿色。
* 默认值为 0xFFFFFF。
* @member {number} egret.TextField#textColor
*/
this._textColor = 0xFFFFFF;
this._strokeColorString = "#000000";
/**
* 表示文本的描边颜色。
* 包含三个 8 位 RGB 颜色成分的数字;例如,0xFF0000 为红色,0x00FF00 为绿色。
* 默认值为 0x000000。
* @member {number} egret.TextField#strokeColor
*/
this._strokeColor = 0x000000;
/**
* 表示描边宽度。
* 0为没有描边。
* 默认值为 0。
* @member {number} egret.TextField#stroke
*/
this._stroke = 0;
/**
* 文本水平对齐方式
* 使用HorizontalAlign定义的常量。
* 默认值为 HorizontalAlign.LEFT。
* @member {string} egret.TextField#textAlign
*/
this._textAlign = "left";
/**
* 文本垂直对齐方式。
* 使用VerticalAlign定义的常量。
* 默认值为 VerticalAlign.TOP。
* @member {string} egret.TextField#verticalAlign
*/
this._verticalAlign = "top";
/**
* 文本字段中最多可包含的字符数(即用户输入的字符数)。
* 脚本可以插入比 maxChars 允许的字符数更多的文本;maxChars 属性仅表示用户可以输入多少文本。如果此属性的值为 0,则用户可以输入无限数量的文本。
* 默认值为 0。
* @type {number}
* @private
*/
this._maxChars = 0;
this._scrollV = -1;
this._maxScrollV = 0;
/**
* 行间距
* 一个整数,表示行与行之间的垂直间距量。
* 默认值为 0。
* @member {number} egret.TextField#lineSpacing
*/
this._lineSpacing = 0;
/**
* 文本行数。【只读】
* @member {number} egret.TextField#numLines
*/
this._numLines = 0;
/**
* 表示字段是否为多行文本字段。注意,此属性仅在type为TextFieldType.INPUT时才有效。
* 如果值为 true,则文本字段为多行文本字段;如果值为 false,则文本字段为单行文本字段。在类型为 TextFieldType.INPUT 的字段中,multiline 值将确定 Enter 键是否创建新行(如果值为 false,则将忽略 Enter 键)。
* 默认值为 false。
* @member {boolean} egret.TextField#multiline
*/
this._multiline = false;
this._isFlow = false;
this._textArr = [];
this._isArrayChanged = false;
this._textMaxWidth = 0; //文本全部显示时宽
this._textMaxHeight = 0; //文本全部显示时高(无行间距)
this._linesArr = [];
}
TextField.prototype.isInput = function () {
return this._type == egret.TextFieldType.INPUT;
};
TextField.prototype._setTouchEnabled = function (value) {
_super.prototype._setTouchEnabled.call(this, value);
if (this.isInput()) {
this._inputEnabled = true;
}
};
Object.defineProperty(TextField.prototype, "type", {
get: function () {
return this._type;
},
set: function (value) {
this._setType(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setType = function (value) {
if (this._type != value) {
this._type = value;
if (this._type == egret.TextFieldType.INPUT) {
if (!this._hasWidthSet) {
this._setWidth(100);
}
if (!this._hasHeightSet) {
this._setHeight(30);
}
//创建stageText
if (this._inputUtils == null) {
this._inputUtils = new egret.InputController();
}
this._inputUtils.init(this);
this._setDirty();
if (this._stage) {
this._inputUtils._addStageText();
}
}
else {
if (this._inputUtils) {
this._inputUtils._removeStageText();
this._inputUtils = null;
}
}
}
};
Object.defineProperty(TextField.prototype, "text", {
get: function () {
return this._getText();
},
set: function (value) {
this._setText(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._getText = function () {
if (this._type == egret.TextFieldType.INPUT) {
return this._inputUtils._getText();
}
return this._text;
};
TextField.prototype._setSizeDirty = function () {
_super.prototype._setSizeDirty.call(this);
this._isArrayChanged = true;
};
TextField.prototype._setTextDirty = function () {
this._setSizeDirty();
};
TextField.prototype._setBaseText = function (value) {
if (value == null) {
value = "";
}
this._isFlow = false;
if (this._text != value || this._displayAsPassword) {
this._setTextDirty();
this._text = value;
var text = "";
if (this._displayAsPassword) {
text = this.changeToPassText(this._text);
}
else {
text = this._text;
}
this.setMiddleStyle([{ text: text }]);
}
};
TextField.prototype._setText = function (value) {
if (value == null) {
value = "";
}
this._setBaseText(value);
if (this._inputUtils) {
this._inputUtils._setText(this._text);
}
};
Object.defineProperty(TextField.prototype, "displayAsPassword", {
get: function () {
return this._displayAsPassword;
},
set: function (value) {
this._setDisplayAsPassword(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setDisplayAsPassword = function (value) {
if (this._displayAsPassword != value) {
this._displayAsPassword = value;
this._setText(this._text);
}
};
Object.defineProperty(TextField.prototype, "fontFamily", {
get: function () {
return this._fontFamily;
},
set: function (value) {
this._setFontFamily(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setFontFamily = function (value) {
if (this._fontFamily != value) {
this._setTextDirty();
this._fontFamily = value;
}
};
Object.defineProperty(TextField.prototype, "size", {
get: function () {
return this._size;
},
set: function (value) {
this._setSize(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setSize = function (value) {
if (this._size != value) {
this._setTextDirty();
this._size = value;
}
};
Object.defineProperty(TextField.prototype, "italic", {
get: function () {
return this._italic;
},
set: function (value) {
this._setItalic(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setItalic = function (value) {
if (this._italic != value) {
this._setTextDirty();
this._italic = value;
}
};
Object.defineProperty(TextField.prototype, "bold", {
get: function () {
return this._bold;
},
set: function (value) {
this._setBold(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setBold = function (value) {
if (this._bold != value) {
this._setTextDirty();
this._bold = value;
}
};
Object.defineProperty(TextField.prototype, "textColor", {
get: function () {
return this._textColor;
},
set: function (value) {
this._setTextColor(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setTextColor = function (value) {
if (this._textColor != value) {
this._setTextDirty();
this._textColor = value;
this._textColorString = egret.toColorString(value);
}
};
Object.defineProperty(TextField.prototype, "strokeColor", {
get: function () {
return this._strokeColor;
},
set: function (value) {
this._setStrokeColor(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setStrokeColor = function (value) {
if (this._strokeColor != value) {
this._setTextDirty();
this._strokeColor = value;
this._strokeColorString = egret.toColorString(value);
}
};
Object.defineProperty(TextField.prototype, "stroke", {
get: function () {
return this._stroke;
},
set: function (value) {
this._setStroke(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setStroke = function (value) {
if (this._stroke != value) {
this._setTextDirty();
this._stroke = value;
}
};
Object.defineProperty(TextField.prototype, "textAlign", {
get: function () {
return this._textAlign;
},
set: function (value) {
this._setTextAlign(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setTextAlign = function (value) {
if (this._textAlign != value) {
this._setTextDirty();
this._textAlign = value;
}
};
Object.defineProperty(TextField.prototype, "verticalAlign", {
get: function () {
return this._verticalAlign;
},
set: function (value) {
this._setVerticalAlign(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setVerticalAlign = function (value) {
if (this._verticalAlign != value) {
this._setTextDirty();
this._verticalAlign = value;
}
};
Object.defineProperty(TextField.prototype, "maxChars", {
get: function () {
return this._maxChars;
},
set: function (value) {
this._setMaxChars(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setMaxChars = function (value) {
if (this._maxChars != value) {
this._maxChars = value;
}
};
Object.defineProperty(TextField.prototype, "scrollV", {
set: function (value) {
this._scrollV = value;
this._setDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "maxScrollV", {
get: function () {
return this._maxScrollV;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "selectionBeginIndex", {
get: function () {
return 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "selectionEndIndex", {
get: function () {
return 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "caretIndex", {
get: function () {
return 0;
},
enumerable: true,
configurable: true
});
TextField.prototype._setSelection = function (beginIndex, endIndex) {
};
Object.defineProperty(TextField.prototype, "lineSpacing", {
get: function () {
return this._lineSpacing;
},
set: function (value) {
this._setLineSpacing(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setLineSpacing = function (value) {
if (this._lineSpacing != value) {
this._setTextDirty();
this._lineSpacing = value;
}
};
TextField.prototype._getLineHeight = function () {
return this._lineSpacing + this._size;
};
Object.defineProperty(TextField.prototype, "numLines", {
get: function () {
return this._numLines;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "multiline", {
get: function () {
return this._multiline;
},
set: function (value) {
this._setMultiline(value);
},
enumerable: true,
configurable: true
});
TextField.prototype._setMultiline = function (value) {
this._multiline = value;
this._setDirty();
};
TextField.prototype.setFocus = function () {
//todo:
egret.Logger.warning("TextField.setFocus 没有实现");
};
TextField.prototype._onRemoveFromStage = function () {
_super.prototype._onRemoveFromStage.call(this);
if (this._type == egret.TextFieldType.INPUT) {
this._inputUtils._removeStageText();
}
};
TextField.prototype._onAddToStage = function () {
_super.prototype._onAddToStage.call(this);
if (this._type == egret.TextFieldType.INPUT) {
this._inputUtils._addStageText();
}
};
TextField.prototype._updateBaseTransform = function () {
_super.prototype._updateTransform.call(this);
};
TextField.prototype._updateTransform = function () {
if (this._type == egret.TextFieldType.INPUT) {
if (this._normalDirty) {
this._clearDirty();
this._inputUtils._updateProperties();
}
else {
this._inputUtils._updateTransform();
}
}
else {
this._updateBaseTransform();
}
};
/**
* @see egret.DisplayObject._render
* @param renderContext
*/
TextField.prototype._render = function (renderContext) {
this.drawText(renderContext);
this._clearDirty();
};
/**
* 测量显示对象坐标与大小
*/
TextField.prototype._measureBounds = function () {
return this.measureText();
};
Object.defineProperty(TextField.prototype, "textFlow", {
get: function () {
return this._textArr;
},
/**
*
*/
set: function (textArr) {
this._isFlow = true;
var text = "";
if (textArr == null)
textArr = [];
for (var i = 0; i < textArr.length; i++) {
var element = textArr[i];
text += element.text;
}
if (this._displayAsPassword) {
this._setBaseText(text);
}
else {
this._text = text;
this.setMiddleStyle(textArr);
}
},
enumerable: true,
configurable: true
});
TextField.prototype.changeToPassText = function (text) {
if (this._displayAsPassword) {
var passText = "";
for (var i = 0, num = text.length; i < num; i++) {
switch (text.charAt(i)) {
case '\n':
passText += "\n";
break;
case '\r':
break;
default:
passText += '*';
}
}
return passText;
}
return text;
};
TextField.prototype.setMiddleStyle = function (textArr) {
this._isArrayChanged = true;
this._textArr = textArr;
this._setSizeDirty();
};
Object.defineProperty(TextField.prototype, "textWidth", {
get: function () {
return this._textMaxWidth;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TextField.prototype, "textHeight", {
get: function () {
return this._textMaxHeight;
},
enumerable: true,
configurable: true
});
TextField.prototype.appendText = function (text) {
this.appendElement({ text: text });
};
TextField.prototype.appendElement = function (element) {
this._textArr.push(element);
this.setMiddleStyle(this._textArr);
};
TextField.prototype._getLinesArr = function () {
if (!this._isArrayChanged) {
return this._linesArr;
}
this._isArrayChanged = false;
var text2Arr = this._textArr;
var renderContext = egret.MainContext.instance.rendererContext;
this._linesArr = [];
this._textMaxHeight = 0;
this._textMaxWidth = 0;
//宽度被设置为0
if (this._hasWidthSet && this._explicitWidth == 0) {
console.warn("文本宽度被设置为0");
this._numLines = 0;
return [{ width: 0, height: 0, elements: [] }];
}
var linesArr = this._linesArr;
var lineW = 0;
var lineH = 0;
var lineCount = 0;
var lineElement;
if (!this._isFlow) {
renderContext.setupFont(this);
}
for (var i = 0; i < text2Arr.length; i++) {
var element = text2Arr[i];
element.style = element.style || {};
var text = element.text.toString();
var textArr = text.split(/(?:\r\n|\r|\n)/);
for (var j = 0; j < textArr.length; j++) {
if (linesArr[lineCount] == null) {
lineElement = { width: 0, height: 0, elements: [] };
linesArr[lineCount] = lineElement;
lineW = 0;
lineH = 0;
}
if (this._type == egret.TextFieldType.INPUT) {
lineH = this._size;
}
else {
lineH = Math.max(lineH, element.style.size || this._size);
}
if (textArr[j] == "") {
}
else {
if (this._isFlow) {
renderContext.setupFont(this, element.style);
}
var w = renderContext.measureText(textArr[j]);
if (!this._hasWidthSet) {
lineW += w;
lineElement.elements.push({ width: w, text: textArr[j], style: element.style });
}
else {
if (lineW + w <= this._explicitWidth) {
lineElement.elements.push({ width: w, text: textArr[j], style: element.style });
lineW += w;
}
else {
var k = 0;
var ww = 0;
var word = textArr[j];
for (; k < word.length; k++) {
w = renderContext.measureText(word.charAt(k));
if (lineW + w > this._explicitWidth) {
break;
}
ww += w;
lineW += w;
}
if (k > 0) {
lineElement.elements.push({ width: ww, text: word.substring(0, k), style: element.style });
textArr[j] = word.substring(k);
}
j--;
}
}
}
if (j < textArr.length - 1) {
lineElement.width = lineW;
lineElement.height = lineH;
this._textMaxWidth = Math.max(this._textMaxWidth, lineW);
this._textMaxHeight += lineH;
if (this._type == egret.TextFieldType.INPUT && !this._multiline) {
this._numLines = linesArr.length;
return linesArr;
}
lineCount++;
}
}
if (i == text2Arr.length - 1 && lineElement) {
lineElement.width = lineW;
lineElement.height = lineH;
this._textMaxWidth = Math.max(this._textMaxWidth, lineW);
this._textMaxHeight += lineH;
}
}
this._numLines = linesArr.length;
return linesArr;
};
TextField.prototype.measureText = function () {
var lines = this._getLinesArr();
if (!lines) {
return egret.Rectangle.identity.initialize(0, 0, 0, 0);
}
var maxWidth = this._hasWidthSet ? this._explicitWidth : this._textMaxWidth;
var maxHeight = this._hasHeightSet ? this._explicitHeight : this._textMaxHeight + (this._numLines - 1) * this._lineSpacing;
return egret.Rectangle.identity.initialize(0, 0, maxWidth, maxHeight);
};
/**
* @private
* @param renderContext
* @returns {Rectangle}
*/
TextField.prototype.drawText = function (renderContext) {
var lines = this._getLinesArr();
if (!lines) {
return;
}
if (!this._isFlow) {
renderContext.setupFont(this);
}
var maxWidth = this._hasWidthSet ? this._explicitWidth : this._textMaxWidth;
var textHeight = this._textMaxHeight + (this._numLines - 1) * this._lineSpacing;
var drawY = 0;
var startLine = 0;
if (this._hasHeightSet) {
if (textHeight < this._explicitHeight) {
var valign = 0;
if (this._verticalAlign == egret.VerticalAlign.MIDDLE)
valign = 0.5;
else if (this._verticalAlign == egret.VerticalAlign.BOTTOM)
valign = 1;
drawY += valign * (this._explicitHeight - textHeight);
}
else if (textHeight > this._explicitHeight) {
startLine = Math.max(this._scrollV - 1, 0);
startLine = Math.min(this._numLines - 1, startLine);
}
}
drawY = Math.round(drawY);
var halign = 0;
if (this._textAlign == egret.HorizontalAlign.CENTER) {
halign = 0.5;
}
else if (this._textAlign == egret.HorizontalAlign.RIGHT) {
halign = 1;
}
var drawX = 0;
for (var i = startLine; i < this._numLines; i++) {
var line = lines[i];
var h = line.height;
drawY += h / 2;
if (i != 0 && this._hasHeightSet && drawY > this._explicitHeight) {
break;
}
drawX = Math.round((maxWidth - line.width) * halign);
for (var j = 0; j < line.elements.length; j++) {
var element = line.elements[j];
var size = element.style.size || this._size;
if (this._type == egret.TextFieldType.INPUT) {
renderContext.drawText(this, element.text, drawX, drawY + (h - size) / 2, element.width);
}
else {
if (this._isFlow) {
renderContext.setupFont(this, element.style);
}
renderContext.drawText(this, element.text, drawX, drawY + (h - size) / 2, element.width, element.style);
}
drawX += element.width;
}
drawY += h / 2 + this._lineSpacing;
}
};
TextField.default_fontFamily = "Arial";
return TextField;
})(egret.DisplayObject);
egret.TextField = TextField;
TextField.prototype.__class__ = "egret.TextField";
})(egret || (egret = {}));
|
export { default, i18nN } from 'ember-cli-gettext/helpers/i18n-n';
|
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
var ColDefUtil = /** @class */ (function () {
function ColDefUtil() {
}
ColDefUtil.STRING_PROPERTIES = [
'headerName',
'columnGroupShow',
'headerClass',
'toolPanelClass',
'headerValueGetter',
'pivotKeys',
'groupId',
'colId',
'sort',
'initialSort',
'field',
'type',
'tooltipComponent',
'tooltipField',
'headerTooltip',
'cellClass',
'showRowGroup',
'template',
'templateUrl',
'filter',
'initialAggFunc',
'aggFunc',
'cellRenderer',
'cellEditor',
'pinned',
'initialPinned',
'chartDataType'
];
ColDefUtil.OBJECT_PROPERTIES = [
'headerGroupComponent',
'headerGroupComponentFramework',
'headerGroupComponentParams',
'cellStyle',
'cellRendererParams',
'cellEditorFramework',
'cellEditorParams',
'pinnedRowCellRendererFramework',
'pinnedRowCellRendererParams',
'filterFramework',
'filterParams',
'pivotValueColumn',
'headerComponent',
'headerComponentFramework',
'headerComponentParams',
'floatingFilterComponent',
'floatingFilterComponentParams',
'floatingFilterComponentFramework',
'tooltipComponent',
'tooltipComponentParams',
'tooltipComponentFramework',
'refData',
'columnsMenuParams'
];
ColDefUtil.ARRAY_PROPERTIES = [
'children',
'sortingOrder',
'allowedAggFuncs',
'menuTabs',
'pivotTotalColumnIds',
'cellClassRules',
'icons'
];
ColDefUtil.NUMBER_PROPERTIES = [
'sortedAt',
'sortIndex',
'initialSortIndex',
'flex',
'initialFlex',
'width',
'initialWidth',
'minWidth',
'maxWidth',
'rowGroupIndex',
'initialRowGroupIndex',
'pivotIndex',
'initialPivotIndex'
];
ColDefUtil.BOOLEAN_PROPERTIES = [
'suppressCellFlash',
'suppressColumnsToolPanel',
'suppressFiltersToolPanel',
'openByDefault',
'marryChildren',
'hide',
'initialHide',
'rowGroup',
'initialRowGroup',
'pivot',
'initialPivot',
'checkboxSelection',
'headerCheckboxSelection',
'headerCheckboxSelectionFilteredOnly',
'suppressMenu',
'suppressMovable',
'lockPosition',
'lockVisible',
'lockPinned',
'unSortIcon',
'suppressSizeToFit',
'suppressAutoSize',
'enableRowGroup',
'enablePivot',
'enableValue',
'editable',
'suppressPaste',
'suppressNavigable',
'enableCellChangeFlash',
'rowDrag',
'dndSource',
'autoHeight',
'wrapText',
'sortable',
'resizable',
'singleClickEdit',
'floatingFilter',
];
ColDefUtil.FUNCTION_PROPERTIES = [
'dndSourceOnRowDrag',
'valueGetter',
'valueSetter',
'filterValueGetter',
'keyCreator',
'cellRenderer',
'cellRendererFramework',
'pinnedRowCellRenderer',
'valueFormatter',
'pinnedRowValueFormatter',
'valueParser',
'comparator',
'equals',
'pivotComparator',
'suppressKeyboardEvent',
'suppressHeaderKeyboardEvent',
'colSpan',
'rowSpan',
'getQuickFilterText',
'newValueHandler',
'onCellValueChanged',
'onCellClicked',
'onCellDoubleClicked',
'onCellContextMenu',
'rowDragText',
'tooltipValueGetter',
'tooltipComponent',
'tooltipComponentFramework',
'cellRendererSelector',
'cellEditorSelector'
];
ColDefUtil.ALL_PROPERTIES = __spreadArrays(ColDefUtil.ARRAY_PROPERTIES, ColDefUtil.OBJECT_PROPERTIES, ColDefUtil.STRING_PROPERTIES, ColDefUtil.NUMBER_PROPERTIES, ColDefUtil.FUNCTION_PROPERTIES, ColDefUtil.BOOLEAN_PROPERTIES);
// used when doing property checks - this causes noise when using frameworks which can add their own fw specific
// properties to colDefs, gridOptions etc
ColDefUtil.FRAMEWORK_PROPERTIES = ['__ob__', '__v_skip', '__metadata__', 'mappedColumnProperties', 'hasChildColumns',
'toColDef', 'createColDefFromGridColumn'];
return ColDefUtil;
}());
export { ColDefUtil };
|
'use strict';
(function() {
// Dishes Controller Spec
describe('Dishes Controller Tests', function() {
// Initialize global variables
var DishesController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Dishes controller.
DishesController = $controller('DishesController', {
$scope: scope
});
}));
it('Should do some controller test', inject(function() {
// The test logic
// ...
}));
});
}()); |
// TODO: expose a function called "info" which prints the date and a logging string.
exports.info = function(msg) {
console.log(msg);
}; |
require('marooka').components.prepareApps(__dirname, {
appsPath: '.',
ignoreApp: 'components',
components: {
containerPath: 'semantic',
globalPath: 'components'
}
});
|
/**
* Render bud files.
* @function renderBud
*/
'use strict'
const coz = require('coz')
const path = require('path')
const co = require('co')
const expandglob = require('expandglob')
/** @lends renderBud */
function renderBud (pattern = '**/.*.bud', options = {}) {
let { force } = options
return co(function * () {
let filenames = yield expandglob(pattern, {
ignore: options.ignore || [
'node_modules/**',
'bower_components/**',
'build/**',
'tmp/**',
'.git/**'
]
})
let results = []
for (let filename of filenames) {
let bud = require(path.resolve(filename))
bud = [].concat(bud).map((bud) =>
Object.assign({}, bud, {
path: bud.path && path.resolve(path.dirname(filename), bud.path),
force: force || bud.force,
src: filename
})
)
let result = yield coz.render(bud, {
prefix: path.relative(process.cwd(), filename)
})
results.push(result)
}
return results
})
}
module.exports = renderBud
|
var _ = require('lodash');
var PNAME = "parent";
var CNAME = "pages";
function findById(node, id) {
if (node == null)
return null;
if (node.id == id)
return node;
if (node[CNAME]) {
for (var i = 0; i < node[CNAME].length; i++) {
var nn = findById(node[CNAME][i], id);
if (nn != null)
return nn;
}
}
return null;
}
exports.findById = findById;
function getNextNode(origin) {
//otherwise, get 'next' node
var next = getFirstChild(origin);
if (next == null)
next = getSibling(origin);
if (next == null)
next = getAncestorsSibling(origin);
if (next == null)
return getRoot(origin);
if (isEmptyNode(next))
return getNextNode(next);
return next;
}
exports.getNextNode = getNextNode;
function getRoot(node){
var p = node;
while (p.parent != null) {
p = p.parent;
}
return p;
}
function isEmptyNode(node){
return node.resources.length==0;
}
function getFirstChild(node) {
var c = node[CNAME];
if (c == null || c.length == 0)
return null;
return c[0];
}
function getSibling(node) {
if (node[PNAME] == null)
return null;
var parent = node[PNAME];
var siblings = parent[CNAME];
var index = siblings.indexOf(node) + 1;
if (index > siblings.length - 1)
return null;
return siblings[index];
}
function getAncestorsSibling(node)
{
var p = node[PNAME];
while (p != null) {
var s = getSibling(p);
if (s != null)
return s;
p = p[PNAME];
}
return null;
}
// getPrevNode: function(origin,idx)
// {
// //step thru images of portfolio
// var children;
// var prev = getPreviousSibling(self.root_node, origin);
// if (prev==null)
// prev = origin._attributes.parent_node;
// if (prev==null)
// prev = self.root_node;
//
// var sel_idx=0;
// if (prev._attributes.data._type=='Portfolio')
// {
// children = prev._attributes.data._attributes.images;
// if (children!=null && children.length!=0)
// sel_idx = children.length - self.portfolio_length_offset;
// }
//
// return {node: prev, idx:sel_idx};
// }
// utils
var site = null;
var lastTime = null;
exports.getSiteMapData = function(Page, add_parents, page_view, next) {
if (arguments.length == 1) {
next = function(){}
add_parents = false;
page_view = default_page_view;
}
else if (arguments.length == 2) {
next = add_parents;
add_parents = false;
page_view = default_page_view;
}
else if (arguments.length == 3) {
next = page_view;
add_parents = false;
page_view = add_parents;
}
if (!site || !lastTime || lastTime.getTime() + 60000 < Date.now()) {
Page.find({})//state: PUBLISHED
.populate('resources')
.exec(function (err, pages) {
if (err) return next(err);
var pages_view = [];
for (var i=0; i<pages.length; i++){
var p = pages[i];
pages_view.push(page_view(p));
}
site = exports.getSiteMap(pages_view, add_parents);
next(null, site);
});
} else {
next(null, site);
}
}
function default_page_view(p) {
return {
id: p.id,
title: p.title,
description: p.description,
url: p.url,
pages: p.pages,
resources: _.map(p.resources, function (o) {
return {description: o.description, public_id: o.meta.public_id}
}),
template: p.template
};
}
exports.getSiteMap = function(pages, add_parents) {
var m = {};
for (var i = 0; i < pages.length; i++)
m[pages[i].id] = pages[i];
var root = null;
for (var i = 0; i < pages.length; i++) {
var p = pages[i];
if (p.url == "/")
root = p;
for (var j = 0; j < p.pages.length; j++) {
p.pages[j] = m[p.pages[j]];
if (add_parents)
p.pages[j].parent = p;
}
}
// s/could go through and delete nulls (the result of unpublished children)
return root;
}
exports.getResources = function(page, resources) {
if (resources == null)
resources = [];
if (page.resources) {
for (var i = 0; i < page.resources.length; i++) {
var r = page.resources[i];
r.source = {page: page._id, url: page.url, index: i};
resources.push(r);
}
}
if (page.pages) {
for (var i = 0; i < page.pages.length; i++) {
exports.getResources(page.pages[i], resources);
}
}
return resources;
}
exports.get_res_bp = function(config){
return "http://res.cloudinary.com/"+config.cloudinaryConfig.cloud_name+"/image/upload";
} |
import React, { Component } from 'react';
import connect from 'react-redux';
import {
AsyncStorage,
StyleSheet,
Text,
TouchableHighlight,
View,
Button,
ScrollView,
TextInput,
Image,
WebView,
ListView,
Linking
} from 'react-native';
import { client_id, client_secret, grant_type } from '../../env.json';
let endPoint = "https://api.producthunt.com/v1/";
const headerInfo = {
accept: "application/json",
"content-type": "application/json",
host: "api.producthunt.com"
};
import postsContainer from '../containers/postsContainer';
import userContainer from '../containers/userContainer';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: '',
credentials: {}
};
}
componentWillMount(){
this.authenticate();
}
authenticate() {
fetch(`${endPoint}oauth/token`, {
method: "POST",
headers: headerInfo,
body: JSON.stringify({
client_id: client_id,
client_secret: client_secret,
grant_type: grant_type,
})
})
.then((res) => { return res.json(); })
.then((response) => { this.setState({ credentials: response }); })
.catch((err) => { alert(err); })
}
fetchPosts() {
fetch(`${endPoint}posts/all?search[topic]=${this.state.searchTerm.toLowerCase()}`, {
method: "GET",
headers: {
headerInfo,
authorization: `Bearer ${this.state.credentials.access_token}`
}
})
.then((res) => { return res.json(); })
.then((response) => this.props.getPosts(response.posts))
.then(this.setState({ searchTerm: ''}))
.catch(() => { alert('Please try a different search term'); })
}
loadPosts() {
return this.props.posts.toJS().map((post, i) => {
return(
<View
key={i}
style={{ height: 70 }}>
<Image
style={ styles.searchItemImg }
source={{ uri: `${post.thumbnail.image_url}` }}/>
<Text
style={ styles.searchItemTitle}>
{ post.name }
</Text>
</View>
)
})
}
render() {
return (
<View style={ styles.searchMain }>
<Text>Search for Products</Text>
<TextInput
style={ styles.searchInput }
onChangeText={ (searchTerm) => this.setState({ searchTerm })}
value={ this.state.searchTerm }
/>
<Button
onPress={ () => this.fetchPosts() }
title='Get Posts'
/>
<ScrollView style={ styles.ScrollView }>
{ this.loadPosts() }
</ScrollView>
</View>
)
}
}
export default postsContainer(
userContainer(Search)
)
const styles = StyleSheet.create({
searchMain: {
backgroundColor: '#fff',
margin: 20,
marginTop: 75,
},
searchInput: {
height: 55,
borderRadius: 3,
borderWidth: 1,
borderColor: '#999999',
marginTop: 10
},
postName: {
width: 100,
height: 100,
},
scrollView: {
top: 20,
height: 400
},
searchItemImg: {
width: 50,
height: 50,
marginLeft: 10
},
searchItemTitle: {
width: 300,
height: 50,
marginLeft: 70,
marginTop: -35,
}
});
|
'use strict'
// https://github.com/timoxley/keycode/blob/master/index.js
// Source: http://jsfiddle.net/vWx8V/
// http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes
/**
* @module Editor
*/
/**
* @method KeyCode
* @param {number|string} key - Can be number(key-code) or string(key-name)
* @return {number|string}
*
* Convenience method returns corresponding value for given keyName or keyCode.
*/
var exports = function(searchInput) {
// Keyboard Events
if (searchInput && 'object' === typeof searchInput) {
let hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode
if (hasKeyCode) searchInput = hasKeyCode
}
// Numbers
if ('number' === typeof searchInput) return names[searchInput]
// Everything else (cast to string)
let search = String(searchInput)
// check codes
let foundNamedKey = codes[search.toLowerCase()]
if (foundNamedKey) return foundNamedKey
// check aliases
foundNamedKey = aliases[search.toLowerCase()]
if (foundNamedKey) return foundNamedKey
// weird character?
if (search.length === 1) return search.charCodeAt(0)
return undefined
}
// Get keycode by key name
// exports.code['enter'] // => 13
let codes = exports.code = exports.codes = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'esc': 27,
'space': 32,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left': 37,
'up': 38,
'right': 39,
'down': 40,
'insert': 45,
'delete': 46,
'command': 91,
'right click': 93,
'numpad *': 106,
'numpad +': 107,
'numpad -': 109,
'numpad .': 110,
'numpad /': 111,
'num lock': 144,
'scroll lock': 145,
'my computer': 182,
'my calculator': 183,
';': 186,
'=': 187,
',': 188,
'-': 189,
'.': 190,
'/': 191,
'`': 192,
'[': 219,
'\\': 220,
']': 221,
"'": 222
}
// Helper aliases
let aliases = exports.aliases = {
'windows': 91,
'⇧': 16,
'⌥': 18,
'⌃': 17,
'⌘': 91,
'ctl': 17,
'control': 17,
'option': 18,
'pause': 19,
'break': 19,
'caps': 20,
'return': 13,
'escape': 27,
'spc': 32,
'pgup': 33,
'pgdn': 33,
'ins': 45,
'del': 46,
'cmd': 91
}
// Programatically add the following
// lower case chars
for (let i = 97; i < 123; i++) codes[String.fromCharCode(i)] = i - 32
// numbers
for (let i = 48; i < 58; i++) codes[i - 48] = i
// function keys
for (let i = 1; i < 13; i++) codes['f' + i] = i + 111
// numpad keys
for (let i = 0; i < 10; i++) codes['numpad ' + i] = i + 96
// Get by code
// exports.name[13] // => 'Enter'
let names = exports.names = exports.title = {} // title for backward compat
// Create reverse mapping
for (let i in codes) names[codes[i]] = i
// Add aliases
for (let alias in aliases) {
codes[alias] = aliases[alias]
}
let KeyCodes = exports |
const express = require('express');
const app = express();
const favicon = require('serve-favicon');
const path = require('path');
const placeRoutes = require('./routes/user_index');
const adminRoutes = require('./routes/admin_index');
app.set('view engine', 'ejs');
// Declare static directory for custom stylesheets
app.use(express.static(path.join(__dirname, '/public')));
// Link to favicon
if (favicon(path.join(__dirname, 'public', 'favicon-globe.ico'))) {
app.use(favicon(path.join(__dirname, 'public', 'favicon-globe.ico')));
}
app.use(placeRoutes);
// Admin routes which require authentication
app.use(adminRoutes);
// Page does not exist
app.get('/*', (req, res) => {
// res.send('Index page!');
res.render('not-found');
});
app.listen(process.env.PORT || 3000, () => {
let port = 3000;
if (process.env.PORT != null) {
port = process.env.PORT;
}
console.log('Server started on port: %d', port);
});
|
import 'whatwg-fetch';
import getBaseUrl from './baseUrl';
const baseUrl = getBaseUrl();
export function getUsers() {
return get('users');
}
export function deleteUser(id) {
return del(`users/${id}`);
}
function get(url) {
return fetch(baseUrl + url).then(onSuccess, onFailure);
}
function del(url) {
const request = new Request(baseUrl + url, {
method: 'DELETE'
});
return fetch(request).then(onSuccess, onFailure);
}
function onSuccess(response) {
return response.json();
}
function onFailure(err) {
console.log(err); // eslint-disable-line no console
}
|
search_result['3812']=["topic_000000000000091F_props--.html","UserVerification Properties",""]; |
export const KODI_CONNECT = 'KODI_CONNECT';
export function kodiConnect(name, host, port, kodiClient) {
return {
type: KODI_CONNECT,
info: {
name,
host,
port
},
kodiClient
};
}
export const UPDATE_CONNECTION_NAME = 'UPDATE_CONNECTION_NAME';
export function connectionName(name) {
return {
type: UPDATE_CONNECTION_NAME,
name
};
}
export const UPDATE_CONNECTION_HOST = 'UPDATE_CONNECTION_HOST';
export function connectionHost(host) {
return {
type: UPDATE_CONNECTION_HOST,
host
};
}
export const UPDATE_CONNECTION_PORT = 'UPDATE_CONNECTION_PORT';
export function connectionPort(port) {
return {
type: UPDATE_CONNECTION_PORT,
port
};
}
|
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var tfjsCore = require('@tensorflow/tfjs-core');
var LongExports = require('long');
var LongExports__default = _interopDefault(LongExports);
var tfjsLayers = require('@tensorflow/tfjs-layers');
var tfjsConverter = require('@tensorflow/tfjs-converter');
var tfjsData = require('@tensorflow/tfjs-data');
var tfjsBackendCpu = require('@tensorflow/tfjs-backend-cpu');
var tfjsBackendWebgl = require('@tensorflow/tfjs-backend-webgl');
const Abs = 'Abs';
const Acos = 'Acos';
const Acosh = 'Acosh';
const Add = 'Add';
const AddN = 'AddN';
const All = 'All';
const Any = 'Any';
const ArgMax = 'ArgMax';
const ArgMin = 'ArgMin';
const Asin = 'Asin';
const Asinh = 'Asinh';
const Atan = 'Atan';
const Atanh = 'Atanh';
const Atan2 = 'Atan2';
const AvgPool = 'AvgPool';
const AvgPoolGrad = 'AvgPoolGrad';
const AvgPool3D = 'AvgPool3D';
const AvgPool3DGrad = 'AvgPool3DGrad';
const BatchMatMul = 'BatchMatMul';
const BatchToSpaceND = 'BatchToSpaceND';
const Bincount = 'Bincount';
const BroadcastTo = 'BroadcastTo';
const BroadcastArgs = 'BroadcastArgs';
const Cast = 'Cast';
const Ceil = 'Ceil';
const ClipByValue = 'ClipByValue';
const Complex = 'Complex';
const ComplexAbs = 'ComplexAbs';
const Concat = 'Concat';
const Conv2D = 'Conv2D';
const Conv2DBackpropFilter = 'Conv2DBackpropFilter';
const Conv2DBackpropInput = 'Conv2DBackpropInput';
const Conv3D = 'Conv3D';
const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';
const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';
const Cos = 'Cos';
const Cosh = 'Cosh';
const Cumsum = 'Cumsum';
const CropAndResize = 'CropAndResize';
const DenseBincount = 'DenseBincount';
const DepthToSpace = 'DepthToSpace';
const DepthwiseConv2dNative = 'DepthwiseConv2dNative';
const DepthwiseConv2dNativeBackpropFilter = 'DepthwiseConv2dNativeBackpropFilter';
const DepthwiseConv2dNativeBackpropInput = 'DepthwiseConv2dNativeBackpropInput';
const Diag = 'Diag';
const Dilation2D = 'Dilation2D';
const Dilation2DBackpropInput = 'Dilation2DBackpropInput';
const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';
const RealDiv = 'RealDiv';
const Einsum = 'Einsum';
const Elu = 'Elu';
const EluGrad = 'EluGrad';
const Erf = 'Erf';
const Equal = 'Equal';
const Exp = 'Exp';
const ExpandDims = 'ExpandDims';
const Expm1 = 'Expm1';
const FFT = 'FFT';
const Fill = 'Fill';
const FlipLeftRight = 'FlipLeftRight';
const Floor = 'Floor';
const FloorDiv = 'FloorDiv';
const FusedBatchNorm = 'FusedBatchNorm';
const GatherV2 = 'GatherV2';
const GatherNd = 'GatherNd';
const Greater = 'Greater';
const GreaterEqual = 'GreaterEqual';
const Identity = 'Identity';
const IFFT = 'IFFT';
const Imag = 'Imag';
const IsFinite = 'IsFinite';
const IsInf = 'IsInf';
const IsNan = 'IsNan';
const LeakyRelu = 'LeakyRelu';
const Less = 'Less';
const LessEqual = 'LessEqual';
const LinSpace = 'LinSpace';
const Log = 'Log';
const Log1p = 'Log1p';
const LogicalAnd = 'LogicalAnd';
const LogicalNot = 'LogicalNot';
const LogicalOr = 'LogicalOr';
const LogSoftmax = 'LogSoftmax';
const LRN = 'LRN';
const LRNGrad = 'LRNGrad';
const Max = 'Max';
const Maximum = 'Maximum';
const MaxPool = 'MaxPool';
const MaxPoolGrad = 'MaxPoolGrad';
const MaxPool3D = 'MaxPool3D';
const MaxPool3DGrad = 'MaxPool3DGrad';
const MaxPoolWithArgmax = 'MaxPoolWithArgmax';
const Mean = 'Mean';
const Min = 'Min';
const Minimum = 'Minimum';
const MirrorPad = 'MirrorPad';
const Mod = 'Mod';
const Multinomial = 'Multinomial';
const Multiply = 'Multiply';
const Neg = 'Neg';
const NotEqual = 'NotEqual';
const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';
const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';
const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';
const OnesLike = 'OnesLike';
const OneHot = 'OneHot';
const Pack = 'Pack';
const PadV2 = 'PadV2';
const Pool = 'Pool';
const Pow = 'Pow';
const Prelu = 'Prelu';
const Prod = 'Prod';
const Range = 'Range';
const Real = 'Real';
const Reciprocal = 'Reciprocal';
const Relu = 'Relu';
const Reshape = 'Reshape';
const ResizeNearestNeighbor = 'ResizeNearestNeighbor';
const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';
const ResizeBilinear = 'ResizeBilinear';
const ResizeBilinearGrad = 'ResizeBilinearGrad';
const Relu6 = 'Relu6';
const Reverse = 'Reverse';
const Round = 'Round';
const Rsqrt = 'Rsqrt';
const ScatterNd = 'ScatterNd';
const Select = 'Select';
const Selu = 'Selu';
const Slice = 'Slice';
const Sin = 'Sin';
const Sinh = 'Sinh';
const Sign = 'Sign';
const Sigmoid = 'Sigmoid';
const Softplus = 'Softplus';
const Sqrt = 'Sqrt';
const Sum = 'Sum';
const SpaceToBatchND = 'SpaceToBatchND';
const SplitV = 'SplitV';
const Softmax = 'Softmax';
const SparseFillEmptyRows = 'SparseFillEmptyRows';
const SparseReshape = 'SparseReshape';
const SparseSegmentMean = 'SparseSegmentMean';
const SparseSegmentSum = 'SparseSegmentSum';
const SparseToDense = 'SparseToDense';
const SquaredDifference = 'SquaredDifference';
const Square = 'Square';
const StridedSlice = 'StridedSlice';
const StringNGrams = 'StringNGrams';
const StringSplit = 'StringSplit';
const StringToHashBucketFast = 'StringToHashBucketFast';
const Sub = 'Sub';
const Tan = 'Tan';
const Tanh = 'Tanh';
const Tile = 'Tile';
const TopK = 'TopK';
const Transform = 'Transform';
const Transpose = 'Transpose';
const Unique = 'Unique';
const Unpack = 'Unpack';
const UnsortedSegmentSum = 'UnsortedSegmentSum';
const ZerosLike = 'ZerosLike';
/**
* TensorFlow.js-only kernels
*/
const Step = 'Step';
const FromPixels = 'FromPixels';
const RotateWithOffset = 'RotateWithOffset';
const _FusedMatMul = '_FusedMatMul';
const FusedConv2D = 'FusedConv2D';
const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const EPSILON_FLOAT32 = 1e-7;
const EPSILON_FLOAT16 = 1e-4;
/** Convenient class for storing tensor-related data. */
class DataStorage {
constructor(backend, dataMover) {
this.backend = backend;
this.dataMover = dataMover;
this.data = new WeakMap();
this.dataIdsCount = 0;
}
get(dataId) {
if (!this.data.has(dataId)) {
this.dataMover.moveData(this.backend, dataId);
}
return this.data.get(dataId);
}
set(dataId, value) {
this.dataIdsCount++;
this.data.set(dataId, value);
}
has(dataId) {
return this.data.has(dataId);
}
delete(dataId) {
this.dataIdsCount--;
return this.data.delete(dataId);
}
numDataIds() {
return this.dataIdsCount;
}
}
/**
* The interface that defines the kernels that should be implemented when
* adding a new backend. New backends don't need to implement every one of the
* methods, this can be done gradually (throw an error for unimplemented
* methods).
*/
class KernelBackend {
refCount(dataId) {
return notYetImplemented('refCount');
}
incRef(dataId) {
return notYetImplemented('incRef');
}
timerAvailable() {
return true;
}
time(f) {
return notYetImplemented('time');
}
read(dataId) {
return notYetImplemented('read');
}
readSync(dataId) {
return notYetImplemented('readSync');
}
numDataIds() {
return notYetImplemented('numDataIds');
}
disposeData(dataId, force) {
return notYetImplemented('disposeData');
}
write(values, shape, dtype) {
return notYetImplemented('write');
}
move(dataId, values, shape, dtype, refCount) {
return notYetImplemented('move');
}
memory() {
return notYetImplemented('memory');
}
/** Returns the highest precision for floats in bits (e.g. 16 or 32) */
floatPrecision() {
return notYetImplemented('floatPrecision');
}
/** Returns the smallest representable number. */
epsilon() {
return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;
}
dispose() {
return notYetImplemented('dispose');
}
}
function notYetImplemented(kernelName) {
throw new Error(`'${kernelName}' not yet implemented or not found in the registry. ` +
`This kernel may not be supported by the tfjs backend you have chosen`);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Shuffles the array in-place using Fisher-Yates algorithm.
*
* ```js
* const a = [1, 2, 3, 4, 5];
* tf.util.shuffle(a);
* console.log(a);
* ```
*
* @param array The array to shuffle in-place.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
// tslint:disable-next-line:no-any
function shuffle(array) {
let counter = array.length;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter) | 0;
// Decrease counter by 1
counter--;
// And swap the last element with it
swap(array, counter, index);
}
}
/**
* Shuffles two arrays in-place the same way using Fisher-Yates algorithm.
*
* ```js
* const a = [1,2,3,4,5];
* const b = [11,22,33,44,55];
* tf.util.shuffleCombo(a, b);
* console.log(a, b);
* ```
*
* @param array The first array to shuffle in-place.
* @param array2 The second array to shuffle in-place with the same permutation
* as the first array.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function shuffleCombo(
// tslint:disable-next-line:no-any
array,
// tslint:disable-next-line:no-any
array2) {
if (array.length !== array2.length) {
throw new Error(`Array sizes must match to be shuffled together ` +
`First array length was ${array.length}` +
`Second array length was ${array2.length}`);
}
let counter = array.length;
let index = 0;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter) | 0;
// Decrease counter by 1
counter--;
// And swap the last element of each array with it
swap(array, counter, index);
swap(array2, counter, index);
}
}
/** Clamps a value to a specified range. */
function clamp(min, x, max) {
return Math.max(min, Math.min(x, max));
}
function nearestLargerEven(val) {
return val % 2 === 0 ? val : val + 1;
}
function swap(object, left, right) {
const temp = object[left];
object[left] = object[right];
object[right] = temp;
}
function sum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
/**
* Returns a sample from a uniform [a, b) distribution.
*
* @param a The minimum support (inclusive).
* @param b The maximum support (exclusive).
* @return A pseudorandom number on the half-open interval [a,b).
*/
function randUniform(a, b) {
const r = Math.random();
return (b * r) + (1 - r) * a;
}
/** Returns the squared Euclidean distance between two vectors. */
function distSquared(a, b) {
let result = 0;
for (let i = 0; i < a.length; i++) {
const diff = Number(a[i]) - Number(b[i]);
result += diff * diff;
}
return result;
}
/**
* Asserts that the expression is true. Otherwise throws an error with the
* provided message.
*
* ```js
* const x = 2;
* tf.util.assert(x === 2, 'x is not 2');
* ```
*
* @param expr The expression to assert (as a boolean).
* @param msg A function that returns the message to report when throwing an
* error. We use a function for performance reasons.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function assert(expr, msg) {
if (!expr) {
throw new Error(typeof msg === 'string' ? msg : msg());
}
}
function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = '') {
assert(arraysEqual(shapeA, shapeB), () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
}
function assertNonNull(a) {
assert(a != null, () => `The input to the tensor constructor must be a non-null value.`);
}
// NOTE: We explicitly type out what T extends instead of any so that
// util.flatten on a nested array of number doesn't try to infer T as a
// number[][], causing us to explicitly type util.flatten<number>().
/**
* Flattens an arbitrarily nested array.
*
* ```js
* const a = [[1, 2], [3, 4], [5, [6, [7]]]];
* const flat = tf.util.flatten(a);
* console.log(flat);
* ```
*
* @param arr The nested array to flatten.
* @param result The destination array which holds the elements.
* @param skipTypedArray If true, avoids flattening the typed arrays. Defaults
* to false.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function flatten(arr, result = [], skipTypedArray = false) {
if (result == null) {
result = [];
}
if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {
for (let i = 0; i < arr.length; ++i) {
flatten(arr[i], result, skipTypedArray);
}
}
else {
result.push(arr);
}
return result;
}
/**
* Returns the size (number of elements) of the tensor given its shape.
*
* ```js
* const shape = [3, 4, 2];
* const size = tf.util.sizeFromShape(shape);
* console.log(size);
* ```
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function sizeFromShape(shape) {
if (shape.length === 0) {
// Scalar.
return 1;
}
let size = shape[0];
for (let i = 1; i < shape.length; i++) {
size *= shape[i];
}
return size;
}
function isScalarShape(shape) {
return shape.length === 0;
}
function arraysEqual(n1, n2) {
if (n1 === n2) {
return true;
}
if (n1 == null || n2 == null) {
return false;
}
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== n2[i]) {
return false;
}
}
return true;
}
function isInt(a) {
return a % 1 === 0;
}
function tanh(x) {
// tslint:disable-next-line:no-any
if (Math.tanh != null) {
// tslint:disable-next-line:no-any
return Math.tanh(x);
}
if (x === Infinity) {
return 1;
}
else if (x === -Infinity) {
return -1;
}
else {
const e2x = Math.exp(2 * x);
return (e2x - 1) / (e2x + 1);
}
}
function sizeToSquarishShape(size) {
const width = Math.ceil(Math.sqrt(size));
return [width, Math.ceil(size / width)];
}
/**
* Creates a new array with randomized indicies to a given quantity.
*
* ```js
* const randomTen = tf.util.createShuffledIndices(10);
* console.log(randomTen);
* ```
*
* @param number Quantity of how many shuffled indicies to create.
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function createShuffledIndices(n) {
const shuffledIndices = new Uint32Array(n);
for (let i = 0; i < n; ++i) {
shuffledIndices[i] = i;
}
shuffle(shuffledIndices);
return shuffledIndices;
}
function rightPad(a, size) {
if (size <= a.length) {
return a;
}
return a + ' '.repeat(size - a.length);
}
function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) {
return new Promise((resolve, reject) => {
let tryCount = 0;
const tryFn = () => {
if (checkFn()) {
resolve();
return;
}
tryCount++;
const nextBackoff = delayFn(tryCount);
if (maxCounter != null && tryCount >= maxCounter) {
reject();
return;
}
setTimeout(tryFn, nextBackoff);
};
tryFn();
});
}
/**
* Given the full size of the array and a shape that may contain -1 as the
* implicit dimension, returns the inferred shape where -1 is replaced.
* E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].
*
* @param shape The shape, which may contain -1 in some dimension.
* @param size The full size (number of elements) of the array.
* @return The inferred shape where -1 is replaced with the inferred size.
*/
function inferFromImplicitShape(shape, size) {
let shapeProd = 1;
let implicitIdx = -1;
for (let i = 0; i < shape.length; ++i) {
if (shape[i] >= 0) {
shapeProd *= shape[i];
}
else if (shape[i] === -1) {
if (implicitIdx !== -1) {
throw Error(`Shapes can only have 1 implicit size. ` +
`Found -1 at dim ${implicitIdx} and dim ${i}`);
}
implicitIdx = i;
}
else if (shape[i] < 0) {
throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);
}
}
if (implicitIdx === -1) {
if (size > 0 && size !== shapeProd) {
throw Error(`Size(${size}) must match the product of shape ${shape}`);
}
return shape;
}
if (shapeProd === 0) {
throw Error(`Cannot infer the missing size in [${shape}] when ` +
`there are 0 elements`);
}
if (size % shapeProd !== 0) {
throw Error(`The implicit shape can't be a fractional number. ` +
`Got ${size} / ${shapeProd}`);
}
const newShape = shape.slice();
newShape[implicitIdx] = size / shapeProd;
return newShape;
}
function parseAxisParam(axis, shape) {
const rank = shape.length;
// Normalize input
axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);
// Check for valid range
assert(axis.every(ax => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but ` +
`got axis ${axis}`);
// Check for only integers
assert(axis.every(ax => isInt(ax)), () => `All values in axis param must be integers but ` +
`got axis ${axis}`);
// Handle negative axis.
return axis.map(a => a < 0 ? rank + a : a);
}
/** Reduces the shape by removing all dimensions of shape 1. */
function squeezeShape(shape, axis) {
const newShape = [];
const keptDims = [];
const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;
const axes = (axis == null || isEmptyArray) ?
null :
parseAxisParam(axis, shape).sort();
let j = 0;
for (let i = 0; i < shape.length; ++i) {
if (axes != null) {
if (axes[j] === i && shape[i] !== 1) {
throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);
}
if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
if (axes[j] <= i) {
j++;
}
}
if (shape[i] !== 1) {
newShape.push(shape[i]);
keptDims.push(i);
}
}
return { newShape, keptDims };
}
function getTypedArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function getArrayFromDType(dtype, size) {
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else if (dtype === 'string') {
values = new Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
return values;
}
function checkConversionForErrors(vals, dtype) {
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);
}
}
}
/** Returns true if the dtype is valid. */
function isValidDtype(dtype) {
return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||
dtype === 'int32' || dtype === 'string';
}
/**
* Returns true if the new type can't encode the old type without loss of
* precision.
*/
function hasEncodingLoss(oldType, newType) {
if (newType === 'complex64') {
return false;
}
if (newType === 'float32' && oldType !== 'complex64') {
return false;
}
if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {
return false;
}
if (newType === 'bool' && oldType === 'bool') {
return false;
}
return true;
}
function isTypedArray(a) {
return a instanceof Float32Array || a instanceof Int32Array ||
a instanceof Uint8Array;
}
function bytesPerElement(dtype) {
if (dtype === 'float32' || dtype === 'int32') {
return 4;
}
else if (dtype === 'complex64') {
return 8;
}
else if (dtype === 'bool') {
return 1;
}
else {
throw new Error(`Unknown dtype ${dtype}`);
}
}
/**
* Returns the approximate number of bytes allocated in the string array - 2
* bytes per character. Computing the exact bytes for a native string in JS is
* not possible since it depends on the encoding of the html page that serves
* the website.
*/
function bytesFromStringArray(arr) {
if (arr == null) {
return 0;
}
let bytes = 0;
arr.forEach(x => bytes += x.length);
return bytes;
}
/** Returns true if the value is a string. */
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isNumber(value) {
return typeof value === 'number';
}
function inferDtype(values) {
if (Array.isArray(values)) {
return inferDtype(values[0]);
}
if (values instanceof Float32Array) {
return 'float32';
}
else if (values instanceof Int32Array || values instanceof Uint8Array) {
return 'int32';
}
else if (isNumber(values)) {
return 'float32';
}
else if (isString(values)) {
return 'string';
}
else if (isBoolean(values)) {
return 'bool';
}
return 'float32';
}
function isFunction(f) {
return !!(f && f.constructor && f.call && f.apply);
}
function nearestDivisor(size, start) {
for (let i = start; i < size; ++i) {
if (size % i === 0) {
return i;
}
}
return size;
}
function computeStrides(shape) {
const rank = shape.length;
if (rank < 2) {
return [];
}
// Last dimension has implicit stride of 1, thus having D-1 (instead of D)
// strides.
const strides = new Array(rank - 1);
strides[rank - 2] = shape[rank - 1];
for (let i = rank - 3; i >= 0; --i) {
strides[i] = strides[i + 1] * shape[i + 1];
}
return strides;
}
function createNestedArray(offset, shape, a, isComplex = false) {
const ret = new Array();
if (shape.length === 1) {
const d = shape[0] * (isComplex ? 2 : 1);
for (let i = 0; i < d; i++) {
ret[i] = a[offset + i];
}
}
else {
const d = shape[0];
const rest = shape.slice(1);
const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
for (let i = 0; i < d; i++) {
ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);
}
}
return ret;
}
// Provide a nested array of TypedArray in given shape.
function toNestedArray(shape, a, isComplex = false) {
if (shape.length === 0) {
// Scalar type should return a single number.
return a[0];
}
const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);
if (size === 0) {
// A tensor with shape zero should be turned into empty list.
return [];
}
if (size !== a.length) {
throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? ' for a complex tensor' : ''}.`);
}
return createNestedArray(0, shape, a, isComplex);
}
function makeOnesTypedArray(size, dtype) {
const array = makeZerosTypedArray(size, dtype);
for (let i = 0; i < array.length; i++) {
array[i] = 1;
}
return array;
}
function makeZerosTypedArray(size, dtype) {
if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
return new Float32Array(size);
}
else if (dtype === 'int32') {
return new Int32Array(size);
}
else if (dtype === 'bool') {
return new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
/**
* Make nested `TypedArray` filled with zeros.
* @param shape The shape information for the nested array.
* @param dtype dtype of the array element.
*/
function makeZerosNestedTypedArray(shape, dtype) {
const size = shape.reduce((prev, curr) => prev * curr, 1);
if (dtype == null || dtype === 'float32') {
return toNestedArray(shape, new Float32Array(size));
}
else if (dtype === 'int32') {
return toNestedArray(shape, new Int32Array(size));
}
else if (dtype === 'bool') {
return toNestedArray(shape, new Uint8Array(size));
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
function assertNonNegativeIntegerDimensions(shape) {
shape.forEach(dimSize => {
assert(Number.isInteger(dimSize) && dimSize >= 0, () => `Tensor must have a shape comprised of positive integers but got ` +
`shape [${shape}].`);
});
}
/**
* Computes flat index for a given location (multidimentionsal index) in a
* Tensor/multidimensional array.
*
* @param locs Location in the tensor.
* @param rank Rank of the tensor.
* @param strides Tensor strides.
*/
function locToIndex(locs, rank, strides) {
if (rank === 0) {
return 0;
}
else if (rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += strides[i] * locs[i];
}
return index;
}
/**
* Computes the location (multidimensional index) in a tensor/multidimentional
* array for a given flat index.
*
* @param index Index in flat array.
* @param rank Rank of tensor.
* @param strides Strides of tensor.
*/
function indexToLoc(index, rank, strides) {
if (rank === 0) {
return [];
}
else if (rank === 1) {
return [index];
}
const locs = new Array(rank);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / strides[i]);
index -= locs[i] * strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
/**
* This method asserts whether an object is a Promise instance.
* @param object
*/
// tslint:disable-next-line: no-any
function isPromise(object) {
// We chose to not use 'obj instanceOf Promise' for two reasons:
// 1. It only reliably works for es6 Promise, not other Promise
// implementations.
// 2. It doesn't work with framework that uses zone.js. zone.js monkey patch
// the async calls, so it is possible the obj (patched) is comparing to a
// pre-patched Promise.
return object && object.then && typeof object.then === 'function';
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
function warn(...msg) {
if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {
console.warn(...msg);
}
}
function log(...msg) {
if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {
console.log(...msg);
}
}
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.
const TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';
/**
* The environment contains evaluated flags as well as the registered platform.
* This is always used as a global singleton and can be retrieved with
* `tf.env()`.
*
* @doc {heading: 'Environment'}
*/
class Environment {
// tslint:disable-next-line: no-any
constructor(global) {
this.global = global;
this.flags = {};
this.flagRegistry = {};
this.urlFlags = {};
// Jasmine spies on this in 'environment_test.ts'
this.getQueryParams = getQueryParams;
this.populateURLFlags();
}
setPlatform(platformName, platform) {
if (this.platform != null) {
warn(`Platform ${this.platformName} has already been set. ` +
`Overwriting the platform with ${platform}.`);
}
this.platformName = platformName;
this.platform = platform;
}
registerFlag(flagName, evaluationFn, setHook) {
this.flagRegistry[flagName] = { evaluationFn, setHook };
// Override the flag value from the URL. This has to happen here because the
// environment is initialized before flags get registered.
if (this.urlFlags[flagName] != null) {
const flagValue = this.urlFlags[flagName];
warn(`Setting feature override from URL ${flagName}: ${flagValue}.`);
this.set(flagName, flagValue);
}
}
async getAsync(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
this.flags[flagName] = await this.evaluateFlag(flagName);
return this.flags[flagName];
}
get(flagName) {
if (flagName in this.flags) {
return this.flags[flagName];
}
const flagValue = this.evaluateFlag(flagName);
if (isPromise(flagValue)) {
throw new Error(`Flag ${flagName} cannot be synchronously evaluated. ` +
`Please use getAsync() instead.`);
}
this.flags[flagName] = flagValue;
return this.flags[flagName];
}
getNumber(flagName) {
return this.get(flagName);
}
getBool(flagName) {
return this.get(flagName);
}
getFlags() {
return this.flags;
}
// For backwards compatibility.
get features() {
return this.flags;
}
set(flagName, value) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot set flag ${flagName} as it has not been registered.`);
}
this.flags[flagName] = value;
if (this.flagRegistry[flagName].setHook != null) {
this.flagRegistry[flagName].setHook(value);
}
}
evaluateFlag(flagName) {
if (this.flagRegistry[flagName] == null) {
throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`);
}
return this.flagRegistry[flagName].evaluationFn();
}
setFlags(flags) {
this.flags = Object.assign({}, flags);
}
reset() {
this.flags = {};
this.urlFlags = {};
this.populateURLFlags();
}
populateURLFlags() {
if (typeof this.global === 'undefined' ||
typeof this.global.location === 'undefined' ||
typeof this.global.location.search === 'undefined') {
return;
}
const urlParams = this.getQueryParams(this.global.location.search);
if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {
const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');
keyValues.forEach(keyValue => {
const [key, value] = keyValue.split(':');
this.urlFlags[key] = parseValue(key, value);
});
}
}
}
function getQueryParams(queryString) {
const params = {};
queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {
decodeParam(params, t[0], t[1]);
return t.join('=');
});
return params;
}
function decodeParam(params, name, value) {
params[decodeURIComponent(name)] = decodeURIComponent(value || '');
}
function parseValue(flagName, value) {
value = value.toLowerCase();
if (value === 'true' || value === 'false') {
return value === 'true';
}
else if (`${+value}` === value) {
return +value;
}
throw new Error(`Could not parse value flag value ${value} for flag ${flagName}.`);
}
/**
* Returns the current environment (a global singleton).
*
* The environment object contains the evaluated feature values as well as the
* active platform.
*
* @doc {heading: 'Environment'}
*/
function env() {
return ENV;
}
let ENV = null;
function setEnvironmentGlobal(environment) {
ENV = environment;
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
// Note that the identifier globalNameSpace is scoped to this module, but will
// always resolve to the same global object regardless of how the module is
// resolved.
// tslint:disable-next-line:no-any
let globalNameSpace;
// tslint:disable-next-line:no-any
function getGlobalNamespace() {
if (globalNameSpace == null) {
// tslint:disable-next-line:no-any
let ns;
if (typeof (window) !== 'undefined') {
ns = window;
}
else if (typeof (global) !== 'undefined') {
ns = global;
}
else if (typeof (process) !== 'undefined') {
ns = process;
}
else if (typeof (self) !== 'undefined') {
ns = self;
}
else {
throw new Error('Could not find a global object');
}
globalNameSpace = ns;
}
return globalNameSpace;
}
// tslint:disable-next-line:no-any
function getGlobalMap() {
const ns = getGlobalNamespace();
if (ns._tfGlobals == null) {
ns._tfGlobals = new Map();
}
return ns._tfGlobals;
}
/**
* Returns a globally accessible 'singleton' object.
*
* @param key the name of the object
* @param init a function to initialize to initialize this object
* the first time it is fetched.
*/
function getGlobal(key, init) {
const globalMap = getGlobalMap();
if (globalMap.has(key)) {
return globalMap.get(key);
}
else {
const singleton = init();
globalMap.set(key, singleton);
return globalMap.get(key);
}
}
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
const kernelRegistry = getGlobal('kernelRegistry', () => new Map());
const gradRegistry = getGlobal('gradRegistry', () => new Map());
/**
* Returns the kernel function (code) associated with the provided names.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*/
function getKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
return kernelRegistry.get(key);
}
/**
* Returns the registered gradient info associated with the provided kernel.
* @param kernelName The official TF kernel name.
*/
function getGradient(kernelName) {
return gradRegistry.get(kernelName);
}
function getKernelsForBackend(backendName) {
const it = kernelRegistry.entries();
const result = [];
while (true) {
const { done, value } = it.next();
if (done) {
break;
}
const [key, config] = value;
const [backend,] = key.split('_');
if (backend === backendName) {
result.push(config);
}
}
return result;
}
/**
* Registers the function (forward pass) for the kernel in a global registry.
*
* @param config A config object with the following properties:
* - `kernelName` The official name of the kernel.
* - `backendName` The official name of the backend.
* - `kernelFunc` The function to run during the forward pass of the kernel.
* - `setupFunc` Optional. Gets called once, after the backend initializes.
* - `disposeFunc` Optional. Gets called once, right before the backend is
* disposed.
*/
function registerKernel(config) {
const { kernelName, backendName } = config;
const key = makeKey(kernelName, backendName);
if (kernelRegistry.has(key)) {
warn(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is already registered`);
}
kernelRegistry.set(key, config);
}
/**
* Registers a gradient function for a given kernel in the global registry,
* to be used during the back-propagation of that kernel.
*
* @param config An object with the following properties:
* - `kernelName` The name of the kernel that the gradient function is for.
* - `gradFunc` The function to run during back-propagation.
*/
function registerGradient(config) {
const { kernelName } = config;
if (gradRegistry.has(kernelName)) {
// TODO (yassogba) after 3.0 assess whether we need to keep this gated
// to debug mode.
if (env().getBool('DEBUG')) {
warn(`Overriding the gradient for '${kernelName}'`);
}
}
gradRegistry.set(kernelName, config);
}
/**
* Removes the kernel function from the registry.
*
* @param kernelName The official name of the kernel.
* @param backendName The official name of the backend.
*
*/
function unregisterKernel(kernelName, backendName) {
const key = makeKey(kernelName, backendName);
if (!kernelRegistry.has(key)) {
throw new Error(`The kernel '${kernelName}' for backend ` +
`'${backendName}' is not registered`);
}
kernelRegistry.delete(key);
}
/** Removes the registered gradient from the global registry. */
function unregisterGradient(kernelName) {
if (!gradRegistry.has(kernelName)) {
throw new Error(`The gradient '${kernelName}' for backend is not registered`);
}
gradRegistry.delete(kernelName);
}
/**
* Finds kernels that have already been registered to a backend and re-registers
* them for a new backend. Useful for registering custom backends.
* @param registeredBackendName Already registered backend.
* @param newBackendName New backend.
*/
function copyRegisteredKernels(registeredBackendName, newBackendName) {
const kernels = getKernelsForBackend(registeredBackendName);
kernels.forEach(kernelConfig => {
const newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName });
registerKernel(newKernelConfig);
});
}
function makeKey(kernelName, backendName) {
return `${backendName}_${kernelName}`;
}
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
// tslint:disable-next-line
const Long =
// tslint:disable-next-line
LongExports__default || LongExports;
function hexToLong(hex) {
return Long.fromString(hex, true, 16);
}
// Some primes between 2^63 and 2^64 for various uses.
// Hex 0xc3a5c85c97cb3127
const k0 = hexToLong('c3a5c85c97cb3127');
// Hex 0xb492b66fbe98f273
const k1 = hexToLong('b492b66fbe98f273');
// Hex 0x9ae16a3b2f90404f
const k2 = hexToLong('9ae16a3b2f90404f');
function shiftMix(val) {
return val.xor(val.shru(47));
}
function fetch(s, offset, numBytes) {
const bytes = s.slice(offset, offset + numBytes);
return Long.fromBytes(Array.from(bytes), true, true);
}
function fetch64(s, offset) {
return fetch(s, offset, 8);
}
function fetch32(s, offset) {
return fetch(s, offset, 4);
}
function rotate64(val, shift) {
// Avoid shifting by 64: doing so yields an undefined result.
return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));
}
function hashLen16(u, v, mul = hexToLong('9ddfea08eb382d69')) {
// Murmur-inspired hashing.
let a = u.xor(v).mul(mul);
a = a.xor(a.shru(47));
let b = v.xor(a).mul(mul);
b = b.xor(b.shru(47));
b = b.mul(mul);
return b;
}
// Return a 16-byte hash for 48 bytes. Quick and dirty.
// Callers do best to use "random-looking" values for a and b.
function weakHashLen32WithSeeds(w, x, y, z, a, b) {
a = a.add(w);
b = rotate64(b.add(a).add(z), 21);
const c = a;
a = a.add(x);
a = a.add(y);
b = b.add(rotate64(a, 44));
return [a.add(z), b.add(c)];
}
function weakHashLen32WithSeedsStr(s, offset, a, b) {
return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b);
}
function hashLen0to16(s, len = s.length) {
if (len >= 8) {
const mul = k2.add(len * 2);
const a = fetch64(s, 0).add(k2);
const b = fetch64(s, len - 8);
const c = rotate64(b, 37).mul(mul).add(a);
const d = rotate64(a, 25).add(b).mul(mul);
return hashLen16(c, d, mul);
}
if (len >= 4) {
const mul = k2.add(len * 2);
const a = fetch32(s, 0);
return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);
}
if (len > 0) {
const a = s[0];
const b = s[len >> 1];
const c = s[len - 1];
const y = a + (b << 8);
const z = len + (c << 2);
return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);
}
return k2;
}
function hashLen17to32(s, len = s.length) {
const mul = k2.add(len * 2);
const a = fetch64(s, 0).mul(k1);
const b = fetch64(s, 8);
const c = fetch64(s, len - 8).mul(mul);
const d = fetch64(s, len - 16).mul(k2);
return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul);
}
function hashLen33to64(s, len = s.length) {
const mul = k2.add(len * 2);
const a = fetch64(s, 0).mul(k2);
const b = fetch64(s, 8);
const c = fetch64(s, len - 8).mul(mul);
const d = fetch64(s, len - 16).mul(k2);
const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);
const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);
const e = fetch64(s, 16).mul(mul);
const f = fetch64(s, 24);
const g = y.add(fetch64(s, len - 32)).mul(mul);
const h = z.add(fetch64(s, len - 24)).mul(mul);
return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul);
}
function fingerPrint64(s, len = s.length) {
const seed = Long.fromNumber(81, true);
if (len <= 32) {
if (len <= 16) {
return hashLen0to16(s, len);
}
else {
return hashLen17to32(s, len);
}
}
else if (len <= 64) {
return hashLen33to64(s, len);
}
// For strings over 64 bytes we loop. Internal state consists of
// 56 bytes: v, w, x, y, and z.
let x = seed;
let y = seed.mul(k1).add(113);
let z = shiftMix(y.mul(k2).add(113)).mul(k2);
let v = [Long.UZERO, Long.UZERO];
let w = [Long.UZERO, Long.UZERO];
x = x.mul(k2).add(fetch64(s, 0));
let offset = 0;
// Set end so that after the loop we have 1 to 64 bytes left to process.
const end = ((len - 1) >> 6) * 64;
const last64 = end + ((len - 1) & 63) - 63;
do {
x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);
y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);
x = x.xor(w[1]);
y = y.add(v[0]).add(fetch64(s, offset + 40));
z = rotate64(z.add(w[0]), 33).mul(k1);
v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));
w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
[z, x] = [x, z];
offset += 64;
} while (offset !== end);
const mul = k1.add(z.and(0xff).shl(1));
// Point to the last 64 bytes of input.
offset = last64;
w[0] = w[0].add((len - 1) & 63);
v[0] = v[0].add(w[0]);
w[0] = w[0].add(v[0]);
x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);
y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);
x = x.xor(w[1].mul(9));
y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));
z = rotate64(z.add(w[0]), 33).mul(mul);
v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));
w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));
[z, x] = [x, z];
return hashLen16(hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul).add(x), mul);
}
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
/**
* Create typed array for scalar value. Used for storing in `DataStorage`.
*/
function createScalarValue(value, dtype) {
if (dtype === 'string') {
return encodeString(value);
}
return toTypedArray([value], dtype);
}
function noConversionNeeded(a, dtype) {
return (a instanceof Float32Array && dtype === 'float32') ||
(a instanceof Int32Array && dtype === 'int32') ||
(a instanceof Uint8Array && dtype === 'bool');
}
function toTypedArray(a, dtype) {
if (dtype === 'string') {
throw new Error('Cannot convert a string[] to a TypedArray');
}
if (Array.isArray(a)) {
a = flatten(a);
}
if (env().getBool('DEBUG')) {
checkConversionForErrors(a, dtype);
}
if (noConversionNeeded(a, dtype)) {
return a;
}
if (dtype == null || dtype === 'float32' || dtype === 'complex64') {
return new Float32Array(a);
}
else if (dtype === 'int32') {
return new Int32Array(a);
}
else if (dtype === 'bool') {
const bool = new Uint8Array(a.length);
for (let i = 0; i < bool.length; ++i) {
if (Math.round(a[i]) !== 0) {
bool[i] = 1;
}
}
return bool;
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
}
/**
* Returns the current high-resolution time in milliseconds relative to an
* arbitrary time in the past. It works across different platforms (node.js,
* browsers).
*
* ```js
* console.log(tf.util.now());
* ```
*
* @doc {heading: 'Util', namespace: 'util'}
*/
function now() {
return env().platform.now();
}
/**
* Returns a platform-specific implementation of
* [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
*
* If `fetch` is defined on the global object (`window`, `process`, etc.),
* `tf.util.fetch` returns that function.
*
* If not, `tf.util.fetch` returns a platform-specific solution.
*
* ```js
* const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');
* // handle response
* ```
*
* @doc {heading: 'Util'}
*/
function fetch$1(path, requestInits) {
return env().platform.fetch(path, requestInits);
}
/**
* Encodes the provided string into bytes using the provided encoding scheme.
*
* @param s The string to encode.
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
function encodeString(s, encoding = 'utf-8') {
encoding = encoding || 'utf-8';
return env().platform.encode(s, encoding);
}
/**
* Decodes the provided bytes into a string using the provided encoding scheme.
* @param bytes The bytes to decode.
*
* @param encoding The encoding scheme. Defaults to utf-8.
*
* @doc {heading: 'Util'}
*/
function decodeString(bytes, encoding = 'utf-8') {
encoding = encoding || 'utf-8';
return env().platform.decode(bytes, encoding);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
class Profiler {
constructor(backendTimer, logger) {
this.backendTimer = backendTimer;
this.logger = logger;
if (logger == null) {
this.logger = new Logger();
}
}
profileKernel(kernelName, inputs, f) {
let outputs;
const holdResultWrapperFn = () => {
outputs = f();
};
let timer;
const start = now();
if (this.backendTimer.timerAvailable()) {
timer = this.backendTimer.time(holdResultWrapperFn);
}
else {
holdResultWrapperFn();
for (const output of outputs) {
output.dataSync();
}
timer = Promise.resolve({ kernelMs: now() - start });
}
if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {
for (let i = 0; i < outputs.length; i++) {
const output = outputs[i];
// Dangling promise here because we don't want to propagate up
// asynchronicity.
output.data().then(tensorVals => {
checkComputationForErrors(tensorVals, output.dtype, kernelName);
});
}
}
const kernelProfile = {
kernelName,
outputs,
inputs,
timeMs: timer.then(timing => timing.kernelMs),
extraInfo: timer.then(timing => timing.getExtraProfileInfo != null ?
timing.getExtraProfileInfo() :
'')
};
return kernelProfile;
}
logKernelProfile(kernelProfile) {
const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile;
outputs.forEach(result => {
Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {
this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]);
});
});
}
}
function checkComputationForErrors(vals, dtype, kernelName) {
if (dtype !== 'float32') {
// Only floating point computations will generate NaN values
return false;
}
for (let i = 0; i < vals.length; i++) {
const num = vals[i];
if (isNaN(num) || !isFinite(num)) {
// Throwing custom exception so behavior is testable.
console.warn(`Found ${num} in the result of '${kernelName}'`);
return true;
}
}
return false;
}
class Logger {
logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) {
const time = typeof timeMs === 'number' ? rightPad(`${timeMs}ms`, 9) :
timeMs['error'];
const paddedName = rightPad(name, 25);
const rank = result.rank;
const size = result.size;
const shape = rightPad(result.shape.toString(), 14);
let inputShapesDescription = '';
for (const name in inputs) {
const input = inputs[name];
if (input != null) {
// The input might be a non-tensor (e.g HTMLImageElement), in which case
// we claim the output shape as input shape.
const inputShape = input.shape || result.shape;
const inputRank = inputShape.length;
inputShapesDescription +=
`${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;
}
}
console.log(`%c${paddedName}\t%c${time}\t%c${rank}D ${shape}\t%c${size}\t%c${inputShapesDescription}\t%c${extraInfo}`, 'font-weight:bold', 'color:red', 'color:blue', 'color: orange', 'color: green', 'color: steelblue');
}
}
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
/**
* Computes a list of TapeNodes that connect x to y, filtering everything else
* out and preserving the order of the original tape elements.
*
* @param tape The tape elements to filter.
* @param xs The input Tensors.
* @param y The output Tensor.
*/
function getFilteredNodesXToY(tape, xs, y) {
// Forward pass to compute all the nodes and Tensors that are transitively a
// function of x.
const tensorsFromX = {};
const nodesFromX = {};
for (let i = 0; i < xs.length; i++) {
tensorsFromX[xs[i].id] = true;
}
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
const nodeInputs = node.inputs;
for (const inputName in nodeInputs) {
const input = nodeInputs[inputName];
let anyInputFromX = false;
for (let j = 0; j < xs.length; j++) {
if (tensorsFromX[input.id]) {
node.outputs.forEach(output => tensorsFromX[output.id] = true);
anyInputFromX = true;
nodesFromX[node.id] = true;
break;
}
}
if (anyInputFromX) {
break;
}
}
}
// Backward pass to find all of the nodes and Tensors that lead to y.
const tensorsLeadToY = {};
tensorsLeadToY[y.id] = true;
const nodesToY = {};
for (let i = tape.length - 1; i >= 0; i--) {
const node = tape[i];
const nodeInputs = node.inputs;
// If any of the outputs lead to y, mark all of the inputs as leading to y.
for (let j = 0; j < node.outputs.length; j++) {
if (tensorsLeadToY[node.outputs[j].id]) {
for (const inputName in nodeInputs) {
tensorsLeadToY[nodeInputs[inputName].id] = true;
nodesToY[node.id] = true;
}
break;
}
}
}
// Return the paths that come from x and lead to y.
const filteredTape = [];
for (let i = 0; i < tape.length; i++) {
const node = tape[i];
if (nodesFromX[node.id] && nodesToY[node.id]) {
// Prune the inputs from the node that aren't a function of x.
const prunedInputs = {};
for (const inputName in node.inputs) {
const nodeInput = node.inputs[inputName];
if (tensorsFromX[nodeInput.id]) {
prunedInputs[inputName] = nodeInput;
}
}
// Copy the node and overwrite inputsAndArgs to the pruned version.
const prunedNode = Object.assign({}, node);
prunedNode.inputs = prunedInputs;
prunedNode.outputs = node.outputs;
filteredTape.push(prunedNode);
}
}
return filteredTape;
}
/**
* Backpropagate gradients through the filtered TapeNodes.
*
* @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map
* is mutated by this method.
* @param filteredTape The filtered TapeNodes to backprop through.
*/
function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy, add) {
// Walk the tape backward and keep a map of Tensor to its gradient.
for (let i = filteredTape.length - 1; i >= 0; i--) {
const node = filteredTape[i];
const dys = [];
node.outputs.forEach(o => {
const gradTensor = tensorAccumulatedGradientMap[o.id];
if (gradTensor != null) {
dys.push(gradTensor);
}
else {
// This particular output is not in the back-propagation subgraph, so it
// does not affect the final output, thus we put null for its dy.
dys.push(null);
}
});
if (node.gradient == null) {
throw new Error(`Cannot compute gradient: gradient function not found ` +
`for ${node.kernelName}.`);
}
// Backprop dy through this node and accumulate gradients over the inputs.
const inputGradients = node.gradient(dys);
for (const inputName in node.inputs) {
if (!(inputName in inputGradients)) {
throw new Error(`Cannot backprop through input ${inputName}. ` +
`Available gradients found: ${Object.keys(inputGradients)}.`);
}
// Call the gradient function.
const dx = tidy(() => inputGradients[inputName]());
if (dx.dtype !== 'float32') {
throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);
}
const x = node.inputs[inputName];
if (!arraysEqual(dx.shape, x.shape)) {
throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ` +
`'${inputName}' has shape '${dx.shape}', which does not match ` +
`the shape of the input '${x.shape}'`);
}
if (tensorAccumulatedGradientMap[x.id] == null) {
tensorAccumulatedGradientMap[x.id] = dx;
}
else {
const curGradient = tensorAccumulatedGradientMap[x.id];
tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);
curGradient.dispose();
}
}
}
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
// Maximum number of values before we decide to show ellipsis.
const FORMAT_LIMIT_NUM_VALS = 20;
// Number of first and last values to show when displaying a, b,...,y, z.
const FORMAT_NUM_FIRST_LAST_VALS = 3;
// Number of significant digits to show.
const FORMAT_NUM_SIG_DIGITS = 7;
function tensorToString(vals, shape, dtype, verbose) {
const strides = computeStrides(shape);
const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);
const rank = shape.length;
const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);
const lines = ['Tensor'];
if (verbose) {
lines.push(` dtype: ${dtype}`);
lines.push(` rank: ${rank}`);
lines.push(` shape: [${shape}]`);
lines.push(` values:`);
}
lines.push(valsLines.map(l => ' ' + l).join('\n'));
return lines.join('\n');
}
function computeMaxSizePerColumn(vals, shape, dtype, strides) {
const n = sizeFromShape(shape);
const numCols = strides[strides.length - 1];
const padPerCol = new Array(numCols).fill(0);
const rank = shape.length;
const valuesOrTuples = dtype === 'complex64' ? createComplexTuples(vals) : vals;
if (rank > 1) {
for (let row = 0; row < n / numCols; row++) {
const offset = row * numCols;
for (let j = 0; j < numCols; j++) {
padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length);
}
}
}
return padPerCol;
}
function valToString(val, pad, dtype) {
let valStr;
if (Array.isArray(val)) {
valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +
`${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;
}
else if (isString(val)) {
valStr = `'${val}'`;
}
else if (dtype === 'bool') {
valStr = boolNumToString(val);
}
else {
valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();
}
return rightPad(valStr, pad);
}
function boolNumToString(v) {
return v === 0 ? 'false' : 'true';
}
function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) {
const storagePerElement = dtype === 'complex64' ? 2 : 1;
const size = shape[0];
const rank = shape.length;
if (rank === 0) {
if (dtype === 'complex64') {
const complexTuple = createComplexTuples(vals);
return [valToString(complexTuple[0], 0, dtype)];
}
if (dtype === 'bool') {
return [boolNumToString(vals[0])];
}
return [vals[0].toString()];
}
if (rank === 1) {
if (size > FORMAT_LIMIT_NUM_VALS) {
const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;
let firstVals = Array.from(vals.slice(0, firstValsSize));
let lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement));
if (dtype === 'complex64') {
firstVals = createComplexTuples(firstVals);
lastVals = createComplexTuples(lastVals);
}
return [
'[' +
firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))
.join(', ') +
', ..., ' +
lastVals
.map((x, i) => valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))
.join(', ') +
']'
];
}
const displayVals = dtype === 'complex64' ? createComplexTuples(vals) :
Array.from(vals);
return [
'[' +
displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))
.join(', ') +
']'
];
}
// The array is rank 2 or more.
const subshape = shape.slice(1);
const substrides = strides.slice(1);
const stride = strides[0] * storagePerElement;
const lines = [];
if (size > FORMAT_LIMIT_NUM_VALS) {
for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, false /* isLast */));
}
lines.push('...');
for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
}
}
else {
for (let i = 0; i < size; i++) {
const start = i * stride;
const end = start + stride;
lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1 /* isLast */));
}
}
const sep = rank === 2 ? ',' : '';
lines[0] = '[' + lines[0] + sep;
for (let i = 1; i < lines.length - 1; i++) {
lines[i] = ' ' + lines[i] + sep;
}
let newLineSep = ',\n';
for (let i = 2; i < rank; i++) {
newLineSep += '\n';
}
lines[lines.length - 1] =
' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);
return lines;
}
function createComplexTuples(vals) {
const complexTuples = [];
for (let i = 0; i < vals.length; i += 2) {
complexTuples.push([vals[i], vals[i + 1]]);
}
return complexTuples;
}
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
/**
* A mutable object, similar to `tf.Tensor`, that allows users to set values
* at locations before converting to an immutable `tf.Tensor`.
*
* See `tf.buffer` for creating a tensor buffer.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class TensorBuffer {
constructor(shape, dtype, values) {
this.dtype = dtype;
this.shape = shape.slice();
this.size = sizeFromShape(shape);
if (values != null) {
const n = values.length;
assert(n === this.size, () => `Length of values '${n}' does not match the size ` +
`inferred by the shape '${this.size}'.`);
}
if (dtype === 'complex64') {
throw new Error(`complex64 dtype TensorBuffers are not supported. Please create ` +
`a TensorBuffer for the real and imaginary parts separately and ` +
`call tf.complex(real, imag).`);
}
this.values = values || getArrayFromDType(dtype, this.size);
this.strides = computeStrides(shape);
}
/**
* Sets a value in the buffer at a given location.
*
* @param value The value to set.
* @param locs The location indices.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
set(value, ...locs) {
if (locs.length === 0) {
locs = [0];
}
assert(locs.length === this.rank, () => `The number of provided coordinates (${locs.length}) must ` +
`match the rank (${this.rank})`);
const index = this.locToIndex(locs);
this.values[index] = value;
}
/**
* Returns the value in the buffer at the provided location.
*
* @param locs The location indices.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
get(...locs) {
if (locs.length === 0) {
locs = [0];
}
let i = 0;
for (const loc of locs) {
if (loc < 0 || loc >= this.shape[i]) {
const msg = `Requested out of range element at ${locs}. ` +
` Buffer shape=${this.shape}`;
throw new Error(msg);
}
i++;
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return this.values[index];
}
locToIndex(locs) {
if (this.rank === 0) {
return 0;
}
else if (this.rank === 1) {
return locs[0];
}
let index = locs[locs.length - 1];
for (let i = 0; i < locs.length - 1; ++i) {
index += this.strides[i] * locs[i];
}
return index;
}
indexToLoc(index) {
if (this.rank === 0) {
return [];
}
else if (this.rank === 1) {
return [index];
}
const locs = new Array(this.shape.length);
for (let i = 0; i < locs.length - 1; ++i) {
locs[i] = Math.floor(index / this.strides[i]);
index -= locs[i] * this.strides[i];
}
locs[locs.length - 1] = index;
return locs;
}
get rank() {
return this.shape.length;
}
/**
* Creates an immutable `tf.Tensor` object from the buffer.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
toTensor() {
return trackerFn().makeTensor(this.values, this.shape, this.dtype);
}
}
// For tracking tensor creation and disposal.
let trackerFn = null;
// Used by chaining methods to call into ops.
let opHandler = null;
// Used to warn about deprecated methods.
let deprecationWarningFn = null;
// This here so that we can use this method on dev branches and keep the
// functionality at master.
// tslint:disable-next-line:no-unused-expression
[deprecationWarningFn];
/**
* An external consumer can register itself as the tensor tracker. This way
* the Tensor class can notify the tracker for every tensor created and
* disposed.
*/
function setTensorTracker(fn) {
trackerFn = fn;
}
/**
* An external consumer can register itself as the op handler. This way the
* Tensor class can have chaining methods that call into ops via the op
* handler.
*/
function setOpHandler(handler) {
opHandler = handler;
}
/**
* Sets the deprecation warning function to be used by this file. This way the
* Tensor class can be a leaf but still use the environment.
*/
function setDeprecationWarningFn(fn) {
deprecationWarningFn = fn;
}
/**
* A `tf.Tensor` object represents an immutable, multidimensional array of
* numbers that has a shape and a data type.
*
* For performance reasons, functions that create tensors do not necessarily
* perform a copy of the data passed to them (e.g. if the data is passed as a
* `Float32Array`), and changes to the data will change the tensor. This is not
* a feature and is not supported. To avoid this behavior, use the tensor before
* changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.
*
* See `tf.tensor` for details on how to create a `tf.Tensor`.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class Tensor {
constructor(shape, dtype, dataId, id) {
/** Whether this tensor has been globally kept. */
this.kept = false;
this.isDisposedInternal = false;
this.shape = shape.slice();
this.dtype = dtype || 'float32';
this.size = sizeFromShape(shape);
this.strides = computeStrides(shape);
this.dataId = dataId;
this.id = id;
this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher');
}
get rank() {
return this.shape.length;
}
/**
* Returns a promise of `tf.TensorBuffer` that holds the underlying data.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async buffer() {
const vals = await this.data();
return opHandler.buffer(this.shape, this.dtype, vals);
}
/**
* Returns a `tf.TensorBuffer` that holds the underlying data.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
bufferSync() {
return opHandler.buffer(this.shape, this.dtype, this.dataSync());
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* asynchronously.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async array() {
const vals = await this.data();
return toNestedArray(this.shape, vals, this.dtype === 'complex64');
}
/**
* Returns the tensor data as a nested array. The transfer of data is done
* synchronously.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
arraySync() {
return toNestedArray(this.shape, this.dataSync(), this.dtype === 'complex64');
}
/**
* Asynchronously downloads the values from the `tf.Tensor`. Returns a
* promise of `TypedArray` that resolves when the computation has finished.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
async data() {
this.throwIfDisposed();
const data = trackerFn().read(this.dataId);
if (this.dtype === 'string') {
const bytes = await data;
try {
return bytes.map(b => decodeString(b));
}
catch (_a) {
throw new Error('Failed to decode the string bytes into utf-8. ' +
'To get the original bytes, call tensor.bytes().');
}
}
return data;
}
/**
* Synchronously downloads the values from the `tf.Tensor`. This blocks the
* UI thread until the values are ready, which can cause performance issues.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
dataSync() {
this.throwIfDisposed();
const data = trackerFn().readSync(this.dataId);
if (this.dtype === 'string') {
try {
return data.map(b => decodeString(b));
}
catch (_a) {
throw new Error('Failed to decode the string bytes into utf-8. ' +
'To get the original bytes, call tensor.bytes().');
}
}
return data;
}
/** Returns the underlying bytes of the tensor's data. */
async bytes() {
this.throwIfDisposed();
const data = await trackerFn().read(this.dataId);
if (this.dtype === 'string') {
return data;
}
else {
return new Uint8Array(data.buffer);
}
}
/**
* Disposes `tf.Tensor` from memory.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
dispose() {
if (this.isDisposed) {
return;
}
trackerFn().disposeTensor(this);
this.isDisposedInternal = true;
}
get isDisposed() {
return this.isDisposedInternal;
}
throwIfDisposed() {
if (this.isDisposed) {
throw new Error(`Tensor is disposed.`);
}
}
/**
* Prints the `tf.Tensor`. See `tf.print` for details.
*
* @param verbose Whether to print verbose information about the tensor,
* including dtype and size.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
print(verbose = false) {
return opHandler.print(this, verbose);
}
/**
* Returns a copy of the tensor. See `tf.clone` for details.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
clone() {
this.throwIfDisposed();
return opHandler.clone(this);
}
/**
* Returns a human-readable description of the tensor. Useful for logging.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
toString(verbose = false) {
const vals = this.dataSync();
return tensorToString(vals, this.shape, this.dtype, verbose);
}
cast(dtype) {
this.throwIfDisposed();
return opHandler.cast(this, dtype);
}
variable(trainable = true, name, dtype) {
this.throwIfDisposed();
return trackerFn().makeVariable(this, trainable, name, dtype);
}
}
Object.defineProperty(Tensor, Symbol.hasInstance, {
value: (instance) => {
// Implementation note: we should use properties of the object that will be
// defined before the constructor body has finished executing (methods).
// This is because when this code is transpiled by babel, babel will call
// classCallCheck before the constructor body is run.
// See https://github.com/tensorflow/tfjs/issues/3384 for backstory.
return !!instance && instance.data != null && instance.dataSync != null &&
instance.throwIfDisposed != null;
}
});
function getGlobalTensorClass() {
// Use getGlobal so that we can augment the Tensor class across package
// boundaries becase the node resolution alg may result in different modules
// being returned for this file depending on the path they are loaded from.
return getGlobal('Tensor', () => {
return Tensor;
});
}
// Global side effect. Cache global reference to Tensor class
getGlobalTensorClass();
/**
* A mutable `tf.Tensor`, useful for persisting state, e.g. for training.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
class Variable extends Tensor {
constructor(initialValue, trainable, name, tensorId) {
super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);
this.trainable = trainable;
this.name = name;
}
/**
* Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have
* the same shape and dtype as the old `tf.Tensor`.
*
* @param newValue New tensor to be assigned to this variable.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
assign(newValue) {
if (newValue.dtype !== this.dtype) {
throw new Error(`dtype of the new value (${newValue.dtype}) and ` +
`previous value (${this.dtype}) must match`);
}
if (!arraysEqual(newValue.shape, this.shape)) {
throw new Error(`shape of the new value (${newValue.shape}) and ` +
`previous value (${this.shape}) must match`);
}
trackerFn().disposeTensor(this);
this.dataId = newValue.dataId;
trackerFn().incRef(this, null /* backend */);
}
dispose() {
trackerFn().disposeVariable(this);
this.isDisposedInternal = true;
}
}
Object.defineProperty(Variable, Symbol.hasInstance, {
value: (instance) => {
return instance instanceof Tensor && instance.assign != null &&
instance.assign instanceof Function;
}
});
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
var Rank;
(function (Rank) {
Rank["R0"] = "R0";
Rank["R1"] = "R1";
Rank["R2"] = "R2";
Rank["R3"] = "R3";
Rank["R4"] = "R4";
Rank["R5"] = "R5";
Rank["R6"] = "R6";
})(Rank || (Rank = {}));
// Looks for upcasting types. Used, for example, in operations with mixed dtype
// inputs.
var UpcastInt32AndMap;
(function (UpcastInt32AndMap) {
UpcastInt32AndMap["float32"] = "float32";
UpcastInt32AndMap["int32"] = "int32";
UpcastInt32AndMap["bool"] = "int32";
UpcastInt32AndMap["complex64"] = "complex64";
})(UpcastInt32AndMap || (UpcastInt32AndMap = {}));
var UpcastBoolAndMap;
(function (UpcastBoolAndMap) {
UpcastBoolAndMap["float32"] = "float32";
UpcastBoolAndMap["int32"] = "int32";
UpcastBoolAndMap["bool"] = "bool";
UpcastBoolAndMap["complex64"] = "complex64";
})(UpcastBoolAndMap || (UpcastBoolAndMap = {}));
var UpcastFloat32AndMap;
(function (UpcastFloat32AndMap) {
UpcastFloat32AndMap["float32"] = "float32";
UpcastFloat32AndMap["int32"] = "float32";
UpcastFloat32AndMap["bool"] = "float32";
UpcastFloat32AndMap["complex64"] = "complex64";
})(UpcastFloat32AndMap || (UpcastFloat32AndMap = {}));
var UpcastComplex64AndMap;
(function (UpcastComplex64AndMap) {
UpcastComplex64AndMap["float32"] = "complex64";
UpcastComplex64AndMap["int32"] = "complex64";
UpcastComplex64AndMap["bool"] = "complex64";
UpcastComplex64AndMap["complex64"] = "complex64";
})(UpcastComplex64AndMap || (UpcastComplex64AndMap = {}));
const upcastTypeMap = {
'float32': UpcastFloat32AndMap,
'int32': UpcastInt32AndMap,
'bool': UpcastBoolAndMap,
'complex64': UpcastComplex64AndMap
};
function upcastType(typeA, typeB) {
if (typeA === 'string' || typeB === 'string') {
if (typeA === 'string' && typeB === 'string') {
return 'string';
}
throw new Error(`Can not upcast ${typeA} with ${typeB}`);
}
return upcastTypeMap[typeA][typeB];
}
/** Returns the output type after summation. */
function sumOutType(type) {
return upcastType(type, 'int32');
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
function makeTypesMatch(a, b) {
if (a.dtype === b.dtype) {
return [a, b];
}
const dtype = upcastType(a.dtype, b.dtype);
return [a.cast(dtype), b.cast(dtype)];
}
function assertTypesMatch(a, b) {
assert(a.dtype === b.dtype, () => `The dtypes of the first(${a.dtype}) and` +
` second(${b.dtype}) input must match`);
}
function isTensorInList(tensor, tensorList) {
return tensorList.some(x => x.id === tensor.id);
}
/**
* Extracts any `Tensor`s found within the provided object.
*
* @param container an object that may be a `Tensor` or may directly contain
* `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it
* is safe to pass any object here, except that `Promise`s are not
* supported.
* @returns An array of `Tensors` found within the passed object. If the
* argument is simply a `Tensor', a list containing that `Tensor` is
* returned. If the object is not a `Tensor` or does not
* contain `Tensors`, an empty list is returned.
*/
function getTensorsInContainer(result) {
const list = [];
const seen = new Set();
walkTensorContainer(result, list, seen);
return list;
}
function walkTensorContainer(container, list, seen) {
if (container == null) {
return;
}
if (container instanceof Tensor) {
list.push(container);
return;
}
if (!isIterable(container)) {
return;
}
// Iteration over keys works also for arrays.
const iterable = container;
for (const k in iterable) {
const val = iterable[k];
if (!seen.has(val)) {
seen.add(val);
walkTensorContainer(val, list, seen);
}
}
}
// tslint:disable-next-line:no-any
function isIterable(obj) {
return Array.isArray(obj) || typeof obj === 'object';
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
function isRegisteredKernelInvocation(kernelInvocation) {
return kernelInvocation.kernelName != null;
}
class EngineState {
constructor() {
// Public since optimizers will use it.
this.registeredVariables = {};
this.nextTapeNodeId = 0;
this.numBytes = 0;
this.numTensors = 0;
this.numStringTensors = 0;
this.numDataBuffers = 0;
// Number of nested tf.grad() statements when computing higher-order
// gradients. E.g. `1` for first-order gradients and `2` for second-order
// gradients. Used to track if the tape should be removed after a backprop.
this.gradientDepth = 0;
// Number of nested kernel calls. When kernel depth is greater than 1, we turn
// off the tape.
this.kernelDepth = 0;
this.scopeStack = [];
/**
* Keeps track of the number of data moves during a kernel execution. We
* maintain a stack since kernels can call other kernels, recursively.
*/
this.numDataMovesStack = [];
this.nextScopeId = 0;
this.tensorInfo = new WeakMap();
this.profiling = false;
this.activeProfile = {
newBytes: 0,
newTensors: 0,
peakBytes: 0,
kernels: [],
result: null,
get kernelNames() {
return Array.from(new Set(this.kernels.map(k => k.name)));
}
};
}
dispose() {
for (const variableName in this.registeredVariables) {
this.registeredVariables[variableName].dispose();
}
}
}
class Engine {
constructor(ENV) {
this.ENV = ENV;
this.registry = {};
this.registryFactory = {};
this.pendingBackendInitId = 0;
this.state = new EngineState();
}
async ready() {
if (this.pendingBackendInit != null) {
return this.pendingBackendInit.then(() => { });
}
if (this.backendInstance != null) {
return;
}
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const success = await this.initializeBackend(backendName).success;
if (success) {
await this.setBackend(backendName);
return;
}
}
throw new Error(`Could not initialize any backends, all backend initializations ` +
`failed.`);
}
get backend() {
if (this.pendingBackendInit != null) {
throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make ` +
`sure to await tf.ready() or await tf.setBackend() before calling ` +
`other methods`);
}
if (this.backendInstance == null) {
const { name, asyncInit } = this.initializeBackendsAndReturnBest();
if (asyncInit) {
throw new Error(`The highest priority backend '${name}' has not yet been ` +
`initialized. Make sure to await tf.ready() or ` +
`await tf.setBackend() before calling other methods`);
}
this.setBackend(name);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(backendName) {
if (!(backendName in this.registry)) {
// If the backend hasn't been initialized but we have a registry entry for
// it, initialize it and return it.
if (backendName in this.registryFactory) {
const { asyncInit } = this.initializeBackend(backendName);
if (asyncInit) {
// Backend is not ready yet.
return null;
}
}
else {
return null;
}
}
return this.registry[backendName];
}
findBackendFactory(backendName) {
if (!(backendName in this.registryFactory)) {
return null;
}
return this.registryFactory[backendName].factory;
}
registerBackend(backendName, factory, priority = 1) {
if (backendName in this.registryFactory) {
warn(`${backendName} backend was already registered. ` +
`Reusing existing backend factory.`);
return false;
}
this.registryFactory[backendName] = { factory, priority };
return true;
}
async setBackend(backendName) {
if (this.registryFactory[backendName] == null) {
throw new Error(`Backend name '${backendName}' not found in registry`);
}
this.backendName = backendName;
if (this.registry[backendName] == null) {
this.backendInstance = null;
const { success, asyncInit } = this.initializeBackend(backendName);
const result = asyncInit ? await success : success;
if (!result) {
return false;
}
}
this.backendInstance = this.registry[backendName];
this.setupRegisteredKernels();
// Reset the profiler.
this.profiler = new Profiler(this.backendInstance);
return true;
}
setupRegisteredKernels() {
const kernels = getKernelsForBackend(this.backendName);
kernels.forEach(kernel => {
if (kernel.setupFunc != null) {
kernel.setupFunc(this.backendInstance);
}
});
}
disposeRegisteredKernels(backendName) {
const kernels = getKernelsForBackend(backendName);
kernels.forEach(kernel => {
if (kernel.disposeFunc != null) {
kernel.disposeFunc(this.registry[backendName]);
}
});
}
/**
* Initializes a backend by looking up the backend name in the factory
* registry and calling the factory method. Returns a boolean representing
* whether the initialization of the backend suceeded. Throws an error if
* there is no backend in the factory registry.
*/
initializeBackend(backendName) {
const registryFactoryEntry = this.registryFactory[backendName];
if (registryFactoryEntry == null) {
throw new Error(`Cannot initialize backend ${backendName}, no registration found.`);
}
try {
const backend = registryFactoryEntry.factory();
/* Test if the factory returns a promise.
Done in a more liberal way than
previous 'Promise.resolve(backend)===backend'
as we needed to account for custom Promise
implementations (e.g. Angular) */
if (backend && !(backend instanceof KernelBackend) &&
typeof backend.then === 'function') {
const promiseId = ++this.pendingBackendInitId;
const success = backend
.then(backendInstance => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.registry[backendName] = backendInstance;
this.pendingBackendInit = null;
return true;
})
.catch(err => {
// Outdated promise. Another backend was set in the meantime.
if (promiseId < this.pendingBackendInitId) {
return false;
}
this.pendingBackendInit = null;
warn(`Initialization of backend ${backendName} failed`);
warn(err.stack || err.message);
return false;
});
this.pendingBackendInit = success;
return { success, asyncInit: true };
}
else {
this.registry[backendName] = backend;
return { success: true, asyncInit: false };
}
}
catch (err) {
warn(`Initialization of backend ${backendName} failed`);
warn(err.stack || err.message);
return { success: false, asyncInit: false };
}
}
removeBackend(backendName) {
if (!(backendName in this.registryFactory)) {
throw new Error(`${backendName} backend not found in registry`);
}
if (this.backendName === backendName && this.pendingBackendInit != null) {
// There is a pending promise of the backend we want to remove. Make it
// obsolete.
this.pendingBackendInitId++;
}
if (backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
delete this.registryFactory[backendName];
// Unset the backend if it is active.
if (this.backendName === backendName) {
this.pendingBackendInit = null;
this.backendName = null;
this.backendInstance = null;
}
}
getSortedBackends() {
if (Object.keys(this.registryFactory).length === 0) {
throw new Error('No backend found in registry.');
}
return Object.keys(this.registryFactory).sort((a, b) => {
// Highest priority comes first.
return this.registryFactory[b].priority -
this.registryFactory[a].priority;
});
}
initializeBackendsAndReturnBest() {
const sortedBackends = this.getSortedBackends();
for (let i = 0; i < sortedBackends.length; i++) {
const backendName = sortedBackends[i];
const { success, asyncInit } = this.initializeBackend(backendName);
if (asyncInit || success) {
return { name: backendName, asyncInit };
}
}
throw new Error(`Could not initialize any backends, all backend initializations ` +
`failed.`);
}
moveData(backend, dataId) {
const info = this.state.tensorInfo.get(dataId);
const srcBackend = info.backend;
const values = this.readSync(dataId);
const refCount = srcBackend.refCount(dataId);
// Delete the tensor from the old backend and move it to the new
// backend.
srcBackend.disposeData(dataId, true);
info.backend = backend;
backend.move(dataId, values, info.shape, info.dtype, refCount);
if (this.shouldCheckForMemLeaks()) {
// Track the number of moves during a kernel execution to correctly
// detect memory leaks.
this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
}
tidy(nameOrFn, fn) {
let name = null;
if (fn == null) {
// Called with only 1 argument.
if (typeof nameOrFn !== 'function') {
throw new Error('Please provide a function to tidy()');
}
fn = nameOrFn;
}
else {
// Called with 2 arguments.
if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {
throw new Error('When calling with two arguments, the first argument ' +
'to tidy() must be a string');
}
if (typeof fn !== 'function') {
throw new Error('When calling with two arguments, the 2nd argument ' +
'to tidy() must be a function');
}
name = nameOrFn;
// TODO(nsthorat,smilkov): Do operation logging and performance
// profiling.
}
let result;
return this.scopedRun(() => this.startScope(name), () => this.endScope(result), () => {
result = fn();
if (result instanceof Promise) {
console.error('Cannot return a Promise inside of tidy.');
}
return result;
});
}
scopedRun(start, end, f) {
start();
try {
const res = f();
end();
return res;
}
catch (ex) {
end();
throw ex;
}
}
nextTensorId() {
return Engine.nextTensorId++;
}
nextVariableId() {
return Engine.nextVariableId++;
}
/**
* This method is called instead of the public-facing tensor.clone() when
* saving a tensor for backwards pass. It makes sure to add the clone
* operation to the tape regardless of being called inside a kernel
* execution.
*/
clone(x) {
const y = ENGINE.runKernel(Identity, { x });
const inputs = { x };
const grad = (dy) => ({
x: () => {
const dtype = 'float32';
const gradInputs = { x: dy };
const attrs = { dtype };
return ENGINE.runKernel(Cast, gradInputs,
// tslint:disable-next-line: no-unnecessary-type-assertion
attrs);
}
});
const saved = [];
this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});
return y;
}
/**
* Execute a kernel with the given name and return the output tensor.
*
* @param kernelName The name of the kernel to execute.
* @param inputs A map of input names to tensors.
* @param attrs A map of attribute names to their values. An attribute is a
* primitive (non-tensor) input to the kernel.
* @param inputsToSave A list of tensors, inputs to save for the backprop
* computation.
* @param outputsToSave A list of booleans, specifying which output to save
* for the backprop computation. These are booleans since the output
* tensors are not visible to the user.
*/
runKernel(kernelName, inputs, attrs) {
if (this.backendName == null) {
// backend has not been initialized yet (backend initialization is lazy
// can be deferred until an op/ kernel is run).
// The below getter has side effects that will try to initialize the
// backend and set properties like this.backendName
// tslint:disable-next-line: no-unused-expression
this.backend;
}
const hasKernel = getKernel(kernelName, this.backendName) != null;
if (!hasKernel) {
throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`);
}
return this.runKernelFunc({ kernelName, inputs, attrs });
}
shouldCheckForMemLeaks() {
return this.ENV.getBool('IS_TEST');
}
checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) {
const numDataIdsAfter = this.backend.numDataIds();
// Count the number of data ids associated with the result of the kernel.
let numOutputDataIds = 0;
outInfos.forEach(info => {
// Complex numbers allocate 3 data ids, one for 'real', one for
// 'imaginary', and one for the container that holds the former two.
numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);
});
// Account for the number of moves during kernel execution. A "data move"
// can happen in the middle of a kernel execution, placing a new (key,value)
// pair in the data storage. Since data moves have net zero effect (we
// always remove the data from the old backend), we have to cancel them out
// when detecting memory leaks.
const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];
const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;
if (dataIdsLeaked > 0) {
throw new Error(`Backend '${this.backendName}' has an internal memory leak ` +
`(${dataIdsLeaked} data ids) after running '${kernelName}'`);
}
}
/**
* Internal helper method to execute a kernel Func
*
* Use `runKernel` to execute kernels from outside of engine.
*/
runKernelFunc(kernelParams) {
let outputs;
let saved = [];
const isTapeOn = this.isTapeOn();
const startingBytecount = this.state.numBytes;
const startingNumTensors = this.state.numTensors;
if (this.shouldCheckForMemLeaks()) {
this.state.numDataMovesStack.push(0);
}
let kernelFunc;
if (this.backendName == null) {
// backend has not been initialized yet (backend initialization is lazy
// can be deferred until an op/ kernel is run).
// The below getter has side effects that will try to initialize the
// backend and set properties like this.backendName
// tslint:disable-next-line: no-unused-expression
this.backend;
}
let out;
const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?
kernelParams.kernelName :
this.state.activeScope != null ? this.state.activeScope.name : '';
// Create the kernelFunc from either a registered kernel OR passed in
// forward/backward functions (used by custom grad). In this context a
// kernelFunc wraps a kernel implementation with some bookkeeping.
if (isRegisteredKernelInvocation(kernelParams)) {
const { kernelName, inputs, attrs } = kernelParams;
if (this.backendName == null) {
// backend has not been initialized yet (backend initialization is lazy
// can be deferred until an op/ kernel is run).
// The below getter has side effects that will try to initialize the
// backend and set properties like this.backendName
// tslint:disable-next-line: no-unused-expression
this.backend;
}
const kernel = getKernel(kernelName, this.backendName);
assert(kernel != null, () => `Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`);
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = kernel.kernelFunc({ inputs, attrs, backend: this.backend });
const outInfos = Array.isArray(out) ? out : [out];
if (this.shouldCheckForMemLeaks()) {
this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);
}
const outTensors = outInfos.map((outInfo) => {
// todo (yassogba) remove this option (Tensor) when node backend
// methods have been modularized and they all return tensorInfo.
// TensorInfos do not have a rank attribute.
if (outInfo.rank != null) {
return outInfo;
}
const { dataId, shape, dtype } = outInfo;
return this.makeTensorFromDataId(dataId, shape, dtype);
});
// Save any required inputs and outputs.
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since there would be no backprop for these tensors
// (which would otherwise dispose them).
if (isTapeOn) {
const tensorsToSave = this.getTensorsForGradient(kernelName, inputs, outTensors);
saved = this.saveTensorsForBackwardMode(tensorsToSave);
}
return outTensors;
};
}
else {
const { forwardFunc } = kernelParams;
// Running a customGrad op.
const saveFunc = (tensors) => {
// Do not save unless we are recording to the tape. Otherwise it would
// cause a mem leak since we would never run backprop, which disposes
// the kept tensors.
if (!isTapeOn) {
return;
}
saved = tensors.map(tensor => this.keep(this.clone(tensor)));
};
kernelFunc = () => {
const numDataIdsBefore = this.backend.numDataIds();
out = this.tidy(() => forwardFunc(this.backend, saveFunc));
const outs = (Array.isArray(out) ? out : [out]);
if (this.shouldCheckForMemLeaks()) {
// Scope name is used to print a more helpful error message if needed.
this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);
}
return outs;
};
}
//
// Run the kernelFunc. Optionally profiling it.
//
const { inputs, attrs } = kernelParams;
const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?
null :
kernelParams.backwardsFunc;
let kernelProfile;
this.scopedRun(
// Stop recording to a tape when running a kernel.
() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {
if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {
outputs = kernelFunc();
}
else {
kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, () => kernelFunc());
if (this.ENV.getBool('DEBUG')) {
this.profiler.logKernelProfile(kernelProfile);
}
outputs = kernelProfile.outputs;
}
});
if (isTapeOn) {
this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);
}
if (this.state.profiling) {
this.state.activeProfile.kernels.push({
name: kernelOrScopeName,
bytesAdded: this.state.numBytes - startingBytecount,
totalBytesSnapshot: this.state.numBytes,
tensorsAdded: this.state.numTensors - startingNumTensors,
totalTensorsSnapshot: this.state.numTensors,
inputShapes: Object.keys(inputs).map(key => inputs[key] != null ? inputs[key].shape : null),
outputShapes: outputs.map(item => item.shape),
kernelTimeMs: kernelProfile.timeMs,
extraInfo: kernelProfile.extraInfo
});
}
return (Array.isArray(out) ? outputs : outputs[0]);
}
/**
* Saves tensors used in forward mode for use in backward mode.
*
* @param tensors the list of tensors to save.
*/
saveTensorsForBackwardMode(tensors) {
const saved = tensors.map(tensor => this.keep(this.clone(tensor)));
return saved;
}
/**
* Returns a list of tensors to save for a given gradient calculation.
*
* @param kernelName name of kernel to look up gradient for.
* @param inputs a map of input tensors.
* @param outputs an array of output tensors from forward mode of kernel.
*/
getTensorsForGradient(kernelName, inputs, outputs) {
const gradConfig = getGradient(kernelName);
if (gradConfig != null) {
const inputsToSave = gradConfig.inputsToSave || [];
const outputsToSave = gradConfig.outputsToSave || [];
// If saveAllInputs is true, all inputs will be saved. Otherwise, inputs
// specified in inputsToSave will be saved.
let inputTensorsToSave;
if (gradConfig.saveAllInputs) {
assert(Array.isArray(inputs), () => 'saveAllInputs is true, expected inputs to be an array.');
inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);
}
else {
inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);
}
const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]);
return inputTensorsToSave.concat(outputTensorsToSave);
}
// We return an empty list rather than throw an error because the kernel we
// are looking up may not actually be relevant to backproping through the
// overall function
//
// See 'does not error if irrelevant (pruned) ops are missing grads' test
// in gradients_test.ts for an example.
return [];
}
/**
* Internal method used by public APIs for tensor creation. Makes a new
* tensor with the provided shape, dtype and values. It always
* creates a new data id and writes the values to the underlying backend.
*/
makeTensor(values, shape, dtype, backend) {
if (values == null) {
throw new Error('Values passed to engine.makeTensor() are null');
}
dtype = dtype || 'float32';
backend = backend || this.backend;
let backendVals = values;
if (dtype === 'string' && isString(values[0])) {
backendVals = values.map(d => encodeString(d));
}
const dataId = backend.write(backendVals, shape, dtype);
const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
this.trackTensor(t, backend);
// Count bytes for string tensors.
if (dtype === 'string') {
const info = this.state.tensorInfo.get(dataId);
const newBytes = bytesFromStringArray(backendVals);
this.state.numBytes += newBytes - info.bytes;
info.bytes = newBytes;
}
return t;
}
/**
* Internal method used by backends. Makes a new tensor
* that is a wrapper around an existing data id. It doesn't create
* a new data id, only increments the ref count used in memory tracking.
*/
makeTensorFromDataId(dataId, shape, dtype, backend) {
dtype = dtype || 'float32';
const t = new Tensor(shape, dtype, dataId, this.nextTensorId());
this.trackTensor(t, backend);
return t;
}
makeVariable(initialValue, trainable = true, name, dtype) {
name = name || this.nextVariableId().toString();
if (dtype != null && dtype !== initialValue.dtype) {
initialValue = initialValue.cast(dtype);
}
const v = new Variable(initialValue, trainable, name, this.nextTensorId());
if (this.state.registeredVariables[v.name] != null) {
throw new Error(`Variable with name ${v.name} was already registered`);
}
this.state.registeredVariables[v.name] = v;
this.incRef(v, this.backend);
return v;
}
trackTensor(a, backend) {
this.state.numTensors++;
if (a.dtype === 'string') {
this.state.numStringTensors++;
}
// Bytes for complex numbers are counted by their components. Bytes for
// string tensors are counted when writing values.
let bytes = 0;
if (a.dtype !== 'complex64' && a.dtype !== 'string') {
bytes = a.size * bytesPerElement(a.dtype);
}
this.state.numBytes += bytes;
if (!this.state.tensorInfo.has(a.dataId)) {
this.state.numDataBuffers++;
this.state.tensorInfo.set(a.dataId, {
backend: backend || this.backend,
dtype: a.dtype,
shape: a.shape,
bytes
});
}
if (!(a instanceof Variable)) {
this.track(a);
}
}
// Track the tensor by dataId and increase the refCount for the dataId in the
// backend.
// TODO(pyu10055): This is currently used by makeVariable method, to increase
// refCount on the backend for the dataId. It can potentially be replaced with
// Identity op indead of calling backend directly.
incRef(a, backend) {
this.trackTensor(a, backend);
this.backend.incRef(a.dataId);
}
removeDataId(dataId, backend) {
if (this.state.tensorInfo.has(dataId) &&
this.state.tensorInfo.get(dataId).backend === backend) {
this.state.tensorInfo.delete(dataId);
this.state.numDataBuffers--;
}
}
disposeTensor(a) {
if (!this.state.tensorInfo.has(a.dataId)) {
return;
}
const info = this.state.tensorInfo.get(a.dataId);
this.state.numTensors--;
if (a.dtype === 'string') {
this.state.numStringTensors--;
this.state.numBytes -= info.bytes;
}
// Don't count bytes for complex numbers as they are counted by their
// components.
if (a.dtype !== 'complex64' && a.dtype !== 'string') {
const bytes = a.size * bytesPerElement(a.dtype);
this.state.numBytes -= bytes;
}
// Remove the reference to dataId if backend dispose the data successfully
if (info.backend.disposeData(a.dataId)) {
this.removeDataId(a.dataId, info.backend);
}
// TODO(nsthorat): Construct an error and save the stack trace for
// debugging when in debug mode. Creating a stack trace is too expensive
// to do unconditionally.
}
disposeVariables() {
for (const varName in this.state.registeredVariables) {
const v = this.state.registeredVariables[varName];
this.disposeVariable(v);
}
}
disposeVariable(v) {
this.disposeTensor(v);
if (this.state.registeredVariables[v.name] != null) {
delete this.state.registeredVariables[v.name];
}
}
memory() {
const info = this.backend.memory();
info.numTensors = this.state.numTensors;
info.numDataBuffers = this.state.numDataBuffers;
info.numBytes = this.state.numBytes;
if (this.state.numStringTensors > 0) {
info.unreliable = true;
if (info.reasons == null) {
info.reasons = [];
}
info.reasons.push('Memory usage by string tensors is approximate ' +
'(2 bytes per character)');
}
return info;
}
async profile(query) {
this.state.profiling = true;
const startBytes = this.state.numBytes;
const startNumTensors = this.state.numTensors;
this.state.activeProfile.kernels = [];
this.state.activeProfile.result = await query();
this.state.profiling = false;
this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));
this.state.activeProfile.newBytes = this.state.numBytes - startBytes;
this.state.activeProfile.newTensors =
this.state.numTensors - startNumTensors;
for (const kernel of this.state.activeProfile.kernels) {
kernel.kernelTimeMs = await kernel.kernelTimeMs;
kernel.extraInfo = await kernel.extraInfo;
}
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) {
const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved };
const gradConfig = getGradient(kernelName);
if (gradConfig != null) {
gradientsFunc = gradConfig.gradFunc;
}
if (gradientsFunc != null) {
tapeNode.gradient = (dys) => {
// TODO(smilkov): To optimize back-prop, pass dys that are not used in
// the backprop graph to the user as null instead of zeros
dys = dys.map((dy, i) => {
if (dy == null) {
const output = outputs[i];
const vals = makeZerosTypedArray(output.size, output.dtype);
return this.makeTensor(vals, output.shape, output.dtype);
}
return dy;
});
// Grad functions of ops with single outputs expect a dy, while ops
// with multiple outputs expect dys (array of dy).
return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);
};
}
this.state.activeTape.push(tapeNode);
}
keep(result) {
result.kept = true;
return result;
}
startTape() {
if (this.state.gradientDepth === 0) {
this.state.activeTape = [];
}
this.state.gradientDepth++;
}
endTape() {
this.state.gradientDepth--;
}
/**
* Start a scope. Use this with endScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
startScope(name) {
const scopeInfo = {
track: [],
name: 'unnamed scope',
id: this.state.nextScopeId++
};
if (name) {
scopeInfo.name = name;
}
this.state.scopeStack.push(scopeInfo);
this.state.activeScope = scopeInfo;
}
/**
* End a scope. Use this with startScope() to achieve the same functionality
* as scope() without the need for a function closure.
*/
endScope(result) {
const tensorsToTrackInParent = getTensorsInContainer(result);
const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(t => t.id));
// Dispose the arrays tracked in this scope.
for (let i = 0; i < this.state.activeScope.track.length; i++) {
const tensor = this.state.activeScope.track[i];
if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {
tensor.dispose();
}
}
const oldScope = this.state.scopeStack.pop();
this.state.activeScope = this.state.scopeStack.length === 0 ?
null :
this.state.scopeStack[this.state.scopeStack.length - 1];
// Track the current result in the parent scope.
tensorsToTrackInParent.forEach(tensor => {
// Only track the tensor if was allocated in the inner scope and is not
// globally kept.
if (!tensor.kept && tensor.scopeId === oldScope.id) {
this.track(tensor);
}
});
}
/**
* Returns gradients of `f` with respect to each of the `xs`. The gradients
* returned are of the same length as `xs`, but some might be null if `f`
* was not a function of that `x`. It also takes optional dy to multiply the
* gradient, which defaults to `1`.
*/
gradients(f, xs, dy, allowNoGradients = false) {
assert(xs.length > 0, () => 'gradients() received an empty list of xs.');
if (dy != null && dy.dtype !== 'float32') {
throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);
}
const y = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy('forward', f));
assert(y instanceof Tensor, () => 'The result y returned by f() must be a tensor.');
// Filter out the nodes that don't connect x => y.
const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);
if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {
throw new Error('Cannot compute gradient of y=f(x) with respect to x. Make sure ' +
'that the f you passed encloses all operations that lead from x ' +
'to y.');
}
return this.tidy('backward', () => {
const accumulatedGradientMap = {};
accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;
// Backprop gradients through the filtered nodes.
backpropagateGradients(accumulatedGradientMap, filteredTape,
// Pass the tidy function to avoid circular dep with `tape.ts`.
f => this.tidy(f),
// Pass an add function to avoide a circular dep with `tape.ts`.
add);
const grads = xs.map(x => accumulatedGradientMap[x.id]);
if (this.state.gradientDepth === 0) {
// This means that we are not computing higher-order gradients
// and can clean up the tape.
this.state.activeTape.forEach(node => {
for (const tensor of node.saved) {
tensor.dispose();
}
});
this.state.activeTape = null;
}
return { value: y, grads };
});
}
customGrad(f) {
assert(isFunction(f), () => 'The f passed in customGrad(f) must be a function.');
return (...inputs) => {
assert(inputs.every(t => t instanceof Tensor), () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +
'tensors');
let res;
const inputMap = {};
inputs.forEach((input, i) => {
inputMap[i] = input;
});
const forwardFunc = (_, save) => {
res = f(...[...inputs, save]);
assert(res.value instanceof Tensor, () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.value` is a tensor');
assert(isFunction(res.gradFunc), () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function.');
return res.value;
};
const backwardsFunc = (dy, saved) => {
const gradRes = res.gradFunc(dy, saved);
const grads = Array.isArray(gradRes) ? gradRes : [gradRes];
assert(grads.length === inputs.length, () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function that returns ' +
'the same number of tensors as inputs passed to f(...).');
assert(grads.every(t => t instanceof Tensor), () => 'The function f passed in customGrad(f) must return an ' +
'object where `obj.gradFunc` is a function that returns ' +
'a list of only tensors.');
const gradMap = {};
grads.forEach((grad, i) => {
gradMap[i] = () => grad;
});
return gradMap;
};
return this.runKernelFunc({
forwardFunc,
backwardsFunc,
inputs: inputMap,
});
};
}
readSync(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.readSync(dataId);
}
read(dataId) {
// Route the read to the correct backend.
const info = this.state.tensorInfo.get(dataId);
return info.backend.read(dataId);
}
async time(query) {
const start = now();
const timingInfo = await this.backend.time(query);
timingInfo.wallMs = now() - start;
return timingInfo;
}
/**
* Tracks a Tensor in the current scope to be automatically cleaned up
* when the current scope ends, and returns the value.
*
* @param result The Tensor to track in the current scope.
*/
track(result) {
if (this.state.activeScope != null) {
result.scopeId = this.state.activeScope.id;
this.state.activeScope.track.push(result);
}
return result;
}
get registeredVariables() {
return this.state.registeredVariables;
}
/**
* Resets the engine state. Removes all backends but does not remove
* registered backend factories.
*/
reset() {
// Make any pending promise obsolete.
this.pendingBackendInitId++;
this.state.dispose();
this.ENV.reset();
this.state = new EngineState();
for (const backendName in this.registry) {
this.disposeRegisteredKernels(backendName);
this.registry[backendName].dispose();
delete this.registry[backendName];
}
this.backendName = null;
this.backendInstance = null;
this.pendingBackendInit = null;
}
}
Engine.nextTensorId = 0;
Engine.nextVariableId = 0;
function ones(shape) {
const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');
return ENGINE.makeTensor(values, shape, 'float32');
}
function getOrMakeEngine() {
const ns = getGlobalNamespace();
if (ns._tfengine == null) {
const environment = new Environment(ns);
ns._tfengine = new Engine(environment);
}
setEnvironmentGlobal(ns._tfengine.ENV);
// Tell the current tensor interface that the global engine is responsible
// for tracking.
setTensorTracker(() => ns._tfengine);
return ns._tfengine;
}
const ENGINE = getOrMakeEngine();
/**
* A implementation of the add op for use within engine and tape.
*
* This allows us to avoid a circular dependency between add.ts and engine.
* It is exported to be available in tape tests.
*/
function add(a, b) {
// We duplicate Add here to avoid a circular dependency with add.ts.
const inputs = { a, b };
return ENGINE.runKernel(Add, inputs);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
function inferShape(val, dtype) {
let firstElem = val;
if (isTypedArray(val)) {
return dtype === 'string' ? [] : [val.length];
}
if (!Array.isArray(val)) {
return []; // Scalar.
}
const shape = [];
while (Array.isArray(firstElem) ||
isTypedArray(firstElem) && dtype !== 'string') {
shape.push(firstElem.length);
firstElem = firstElem[0];
}
if (Array.isArray(val) &&
env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {
deepAssertShapeConsistency(val, shape, []);
}
return shape;
}
function deepAssertShapeConsistency(val, shape, indices) {
indices = indices || [];
if (!(Array.isArray(val)) && !isTypedArray(val)) {
assert(shape.length === 0, () => `Element arr[${indices.join('][')}] is a primitive, ` +
`but should be an array/TypedArray of ${shape[0]} elements`);
return;
}
assert(shape.length > 0, () => `Element arr[${indices.join('][')}] should be a primitive, ` +
`but is an array of ${val.length} elements`);
assert(val.length === shape[0], () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +
`elements, but has ${val.length} elements`);
const subShape = shape.slice(1);
for (let i = 0; i < val.length; ++i) {
deepAssertShapeConsistency(val[i], subShape, indices.concat(i));
}
}
function assertDtype(expectedDtype, actualDType, argName, functionName) {
if (expectedDtype === 'string_or_numeric') {
return;
}
if (expectedDtype == null) {
throw new Error(`Expected dtype cannot be null.`);
}
if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||
expectedDtype === 'numeric' && actualDType === 'string') {
throw new Error(`Argument '${argName}' passed to '${functionName}' must ` +
`be ${expectedDtype} tensor, but got ${actualDType} tensor`);
}
}
function convertToTensor(x, argName, functionName, parseAsDtype = 'numeric') {
if (x instanceof Tensor) {
assertDtype(parseAsDtype, x.dtype, argName, functionName);
return x;
}
let inferredDtype = inferDtype(x);
// If the user expects a bool/int/float, use that info to update the
// inferredDtype when it is not a string.
if (inferredDtype !== 'string' &&
['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {
inferredDtype = parseAsDtype;
}
assertDtype(parseAsDtype, inferredDtype, argName, functionName);
if ((x == null) ||
(!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&
typeof x !== 'boolean' && typeof x !== 'string')) {
const type = x == null ? 'null' : x.constructor.name;
throw new Error(`Argument '${argName}' passed to '${functionName}' must be a ` +
`Tensor or TensorLike, but got '${type}'`);
}
const inferredShape = inferShape(x, inferredDtype);
if (!isTypedArray(x) && !Array.isArray(x)) {
x = [x];
}
const skipTypedArray = true;
const values = inferredDtype !== 'string' ?
toTypedArray(x, inferredDtype) :
flatten(x, [], skipTypedArray);
return ENGINE.makeTensor(values, inferredShape, inferredDtype);
}
function convertToTensorArray(arg, argName, functionName, parseAsDtype = 'numeric') {
if (!Array.isArray(arg)) {
throw new Error(`Argument ${argName} passed to ${functionName} must be a ` +
'`Tensor[]` or `TensorLike[]`');
}
const tensors = arg;
return tensors.map((t, i) => convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
const OP_SCOPE_SUFFIX = '__op';
/**
* Used for wrapping functions that perform math operations on
* Tensors. The function will be wrapped in a named scope that cleans all
* memory usage after the function is done.
*/
function op(f) {
const keys = Object.keys(f);
if (keys.length !== 1) {
throw new Error(`Please provide an object with a single key ` +
`(operation name) mapping to a function. Got an object with ` +
`${keys.length} keys.`);
}
let opName = keys[0];
const fn = f[opName];
// Strip the underscore from the end of the function name.
if (opName.endsWith('_')) {
opName = opName.substring(0, opName.length - 1);
}
// add an __op suffix to distinguish ops from kernels in tf.profile
opName = opName + OP_SCOPE_SUFFIX;
// tslint:disable-next-line:no-any
const f2 = (...args) => {
ENGINE.startScope(opName);
try {
const result = fn(...args);
if (isPromise(result)) {
console.error('Cannot return a Promise inside of tidy.');
}
ENGINE.endScope(result);
return result;
}
catch (ex) {
ENGINE.endScope(null);
throw ex;
}
};
Object.defineProperty(f2, 'name', { value: opName, configurable: true });
// tslint:disable-next-line:no-any
return f2;
}
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Casts a `tf.Tensor` to a new dtype.
*
* ```js
* const x = tf.tensor1d([1.5, 2.5, 3]);
* tf.cast(x, 'int32').print();
* ```
* @param x The input tensor to be casted.
* @param dtype The dtype to cast the input tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function cast_(x, dtype) {
const $x = convertToTensor(x, 'x', 'cast');
// Sanity checks.
if (!isValidDtype(dtype)) {
throw new Error(`Failed to cast to unknown dtype ${dtype}`);
}
if (dtype === 'string' && $x.dtype !== 'string' ||
dtype !== 'string' && $x.dtype === 'string') {
throw new Error('Only strings can be casted to strings');
}
const inputs = { x: $x };
const attrs = { dtype };
return ENGINE.runKernel(Cast, inputs, attrs);
}
const cast = op({ cast_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.
*
* We also expose `tf.mulStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([2, 3, 4, 5]);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
*
* ```js
* // Broadcast mul a with b.
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.scalar(5);
*
* a.mul(b).print(); // or tf.mul(a, b)
* ```
* @param a The first tensor to multiply.
* @param b The second tensor to multiply. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function mul_(a, b) {
let $a = convertToTensor(a, 'a', 'mul');
let $b = convertToTensor(b, 'b', 'mul');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Multiply, inputs);
}
const mul = op({ mul_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha * x`
*
* ```js
* const x = tf.tensor1d([0, 2, -1, -3]);
*
* x.step(.5).print(); // or tf.step(x, .5)
* ```
* @param x The input tensor.
* @param alpha The gradient when input is negative.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function step_(x, alpha = 0.0) {
const $x = convertToTensor(x, 'x', 'step');
const inputs = { x: $x };
const attrs = { alpha };
return ENGINE.runKernel(Step, inputs, attrs);
}
const step = op({ step_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const absGradConfig = {
kernelName: Abs,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, step(cast(x, 'float32'), -1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
* The result is rounded with floor function.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.floorDiv(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.floorDiv(b).print(); // or tf.floorDiv(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function floorDiv_(a, b) {
let $a = convertToTensor(a, 'a', 'floorDiv');
let $b = convertToTensor(b, 'b', 'floorDiv');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(FloorDiv, inputs);
}
const floorDiv = op({ floorDiv_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
*
* a.div(b).print(); // or tf.div(a, b)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function div_(a, b) {
let $a = convertToTensor(a, 'a', 'div');
let $b = convertToTensor(b, 'b', 'div');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'int32' && $b.dtype === 'int32') {
return floorDiv($a, $b);
}
const inputs = { a: $a, b: $b };
const attrs = {};
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(RealDiv, inputs, attrs);
}
const div = op({ div_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes `-1 * x` element-wise.
*
* ```js
* const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);
*
* x.neg().print(); // or tf.neg(x)
* ```
*
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function neg_(x) {
const $x = convertToTensor(x, 'x', 'neg');
const inputs = { x: $x };
return ENGINE.runKernel(Neg, inputs);
}
const neg = op({ neg_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/** This is shared code across all tensor creation methods. */
function makeTensor(values, shape, inferredShape, dtype) {
if (dtype == null) {
dtype = inferDtype(values);
}
if (dtype === 'complex64') {
throw new Error(`Cannot construct a complex64 tensor directly. ` +
`Please use tf.complex(real, imag).`);
}
if (!isTypedArray(values) && !Array.isArray(values) &&
typeof values !== 'number' && typeof values !== 'boolean' &&
typeof values !== 'string') {
throw new Error('values passed to tensor(values) must be a number/boolean/string or ' +
'an array of numbers/booleans/strings, or a TypedArray');
}
if (shape != null) {
assertNonNegativeIntegerDimensions(shape);
const providedSize = sizeFromShape(shape);
const inferredSize = sizeFromShape(inferredShape);
assert(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ` +
`${providedSize} values but has ${inferredSize}`);
for (let i = 0; i < inferredShape.length; ++i) {
const inferred = inferredShape[i];
const flatDimsDontMatch = i === inferredShape.length - 1 ?
inferred !== sizeFromShape(shape.slice(i)) :
true;
assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape ` +
`(${inferredShape}) does not match the provided ` +
`shape (${shape}). `);
}
}
if (!isTypedArray(values) && !Array.isArray(values)) {
values = [values];
}
shape = shape || inferredShape;
values = dtype !== 'string' ?
toTypedArray(values, dtype) :
flatten(values, [], true);
return ENGINE.makeTensor(values, shape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.scalar` as it makes the code more readable.
*
* ```js
* tf.scalar(3.14).print();
* ```
*
* @param value The value of the scalar.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function scalar(value, dtype) {
if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&
dtype !== 'complex64') {
throw new Error('Error creating a new Scalar: value must be a primitive ' +
'(number|boolean|string)');
}
if (dtype === 'string' && isTypedArray(value) &&
!(value instanceof Uint8Array)) {
throw new Error('When making a scalar from encoded string, ' +
'the value must be `Uint8Array`.');
}
const shape = [];
const inferredShape = [];
return makeTensor(value, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.sqrt().print(); // or tf.sqrt(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sqrt_(x) {
const $x = convertToTensor(x, 'x', 'sqrt');
const inputs = { x: $x };
return ENGINE.runKernel(Sqrt, inputs);
}
const sqrt = op({ sqrt_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Computes square of `x` element-wise: `x ^ 2`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);
*
* x.square().print(); // or tf.square(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function square_(x) {
const $x = convertToTensor(x, 'x', 'square');
const attrs = {};
return ENGINE.runKernel('Square', { x: $x }, attrs);
}
const square = op({ square_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.tensor1d([1, 2, 3, 4]);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
*
* ```js
* // Broadcast subtract a with b.
* const a = tf.tensor1d([10, 20, 30, 40]);
* const b = tf.scalar(5);
*
* a.sub(b).print(); // or tf.sub(a, b)
* ```
* @param a The first `tf.Tensor` to subtract from.
* @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function sub_(a, b) {
let $a = convertToTensor(a, 'a', 'sub');
let $b = convertToTensor(b, 'b', 'sub');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Sub, inputs);
}
const sub = op({ sub_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const acosGradConfig = {
kernelName: Acos,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = square(cast(x, 'float32'));
const b = sqrt(sub(scalar(1), a));
return neg(div(dy, b));
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const acoshGradConfig = {
kernelName: Acosh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = sqrt(sub(square(cast(x, 'float32')), 1));
return div(dy, a);
}
};
}
};
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the dimensions in the input shape that are broadcasted to
* produce the provided output shape.
*
* The returned dimensions are 0-indexed and sorted. An example:
* inShape = [4, 1, 3]
* outShape = [5, 4, 3, 3]
* result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.
*/
function getBroadcastDims(inShape, outShape) {
const inRank = inShape.length;
const dims = [];
for (let i = 0; i < inRank; i++) {
const dim = inRank - 1 - i;
const a = inShape[dim] || 1;
const b = outShape[outShape.length - 1 - i] || 1;
if (b > 1 && a === 1) {
dims.unshift(dim);
}
}
return dims;
}
/**
* Returns the axes in the output space that should be reduced to produce
* the input space.
*/
function getReductionAxes(inShape, outShape) {
const result = [];
for (let i = 0; i < outShape.length; i++) {
const inDim = inShape[inShape.length - i - 1];
const outAxis = outShape.length - i - 1;
const outDim = outShape[outAxis];
if (inDim == null || (inDim === 1 && outDim > 1)) {
result.unshift(outAxis);
}
}
return result;
}
function assertAndGetBroadcastShape(shapeA, shapeB) {
const result = [];
const l = Math.max(shapeA.length, shapeB.length);
for (let i = 0; i < l; i++) {
let a = shapeA[shapeA.length - i - 1];
if (a == null) {
a = 1;
}
let b = shapeB[shapeB.length - i - 1];
if (b == null) {
b = 1;
}
if (a === 1) {
result.unshift(b);
}
else if (b === 1) {
result.unshift(a);
}
else if (a !== b) {
const errMsg = `Operands could not be broadcast together with shapes ` +
`${shapeA} and ${shapeB}.`;
throw Error(errMsg);
}
else {
result.unshift(a);
}
}
return result;
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reshapes a `tf.Tensor` to a given shape.
*
* Given an input tensor, returns a new tensor with the same values as the
* input tensor with shape `shape`.
*
* If one component of shape is the special value -1, the size of that
* dimension is computed so that the total size remains constant. In
* particular, a shape of [-1] flattens into 1-D. At most one component of
* shape can be -1.
*
* If shape is 1-D or higher, then the operation returns a tensor with shape
* shape filled with the values of tensor. In this case, the number of
* elements implied by shape must be the same as the number of elements in
* tensor.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.reshape([2, 2]).print();
* ```
*
* @param x The input tensor to be reshaped.
* @param shape An array of integers defining the output tensor shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function reshape_(x, shape) {
const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');
const inputs = { x: $x };
const attrs = { shape };
return ENGINE.runKernel(Reshape, inputs, attrs);
}
const reshape = op({ reshape_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the sum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If axes has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.sum().print(); // or tf.sum(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.sum(axis).print(); // or tf.sum(x, axis)
* ```
*
* @param x The input tensor to compute the sum over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function sum_(x, axis = null, keepDims = false) {
let $x = convertToTensor(x, 'x', 'sum');
if ($x.dtype === 'bool') {
$x = cast($x, 'int32');
}
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Sum, inputs, attrs);
}
const sum$1 = op({ sum_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const addGradConfig = {
kernelName: Add,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const addNGradConfig = {
kernelName: AddN,
saveAllInputs: true,
gradFunc: (dy, saved) => {
const ders = {};
saved.forEach((_, i) => {
ders[i] = () => dy.clone();
});
return ders;
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 0 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.zerosLike(x).print();
* ```
*
* @param x The tensor of required shape.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function zerosLike_(x) {
const $x = convertToTensor(x, 'x', 'zerosLike');
const inputs = { x: $x };
return ENGINE.runKernel(ZerosLike, inputs);
}
const zerosLike = op({ zerosLike_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const argMaxGradConfig = {
kernelName: ArgMax,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => zerosLike(x) };
}
};
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const argMinGradConfig = {
kernelName: ArgMin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => zerosLike(x) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const asinGradConfig = {
kernelName: Asin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, sqrt(sub(scalar(1), square(cast(x, 'float32'))))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.
*
*
* ```js
* const a = tf.tensor1d([1, 2, 3, 4]);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
*
* ```js
* // Broadcast add a with b.
* const a = tf.scalar(5);
* const b = tf.tensor1d([10, 20, 30, 40]);
*
* a.add(b).print(); // or tf.add(a, b)
* ```
* @param a The first `tf.Tensor` to add.
* @param b The second `tf.Tensor` to add. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function add_(a, b) {
let $a = convertToTensor(a, 'a', 'add');
let $b = convertToTensor(b, 'b', 'add');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Add, inputs);
}
const add$1 = op({ add_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const asinhGradConfig = {
kernelName: Asinh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const a = sqrt(add$1(scalar(1), square(cast(x, 'float32'))));
return div(dy, a);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const atan2GradConfig = {
kernelName: Atan2,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const d = add$1(square(a), square(b));
let res = mul(dy, div(b, d));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
const d = add$1(square(a), square(b));
let res = neg(mul(dy, div(a, d)));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const atanGradConfig = {
kernelName: Atan,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, add$1(square(cast(x, 'float32')), 1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const atanhGradConfig = {
kernelName: Atanh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, sub(scalar(1), square(cast(x, 'float32')))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the backprop of a 3d avg pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank4 of shape
* [batchSize, depth, height, width, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function avgPool3dGrad_(dy, input, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'avgPool3dGrad');
const $input = convertToTensor(input, 'input', 'avgPool3dGrad');
let dy5D = $dy;
let input5D = $input;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]
]);
}
assert(dy5D.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
assert(input5D.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool3dGrad: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy5D, input: input5D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(AvgPool3DGrad, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3dGrad = op({ avgPool3dGrad_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const avgPool3DGradConfig = {
kernelName: AvgPool3D,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, pad, dimRoundingMode } = attrs;
return {
x: () => avgPool3dGrad(dy, x, filterSize, strides, pad, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the backprop of an 2D avg pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The input image, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm used in the forward prop of the op.
* 'same', 'valid', for more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
*/
function avgPoolGrad_(dy, input, filterSize, strides, pad) {
const $dy = convertToTensor(dy, 'dy', 'avgPoolGrad');
const $input = convertToTensor(input, 'input', 'avgPoolGrad');
assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy (${$dy.rank})`);
let input4D = $input;
let dy4D = $dy;
let reshapedTo4D = false;
if ($input.rank === 3) {
reshapedTo4D = true;
input4D =
reshape($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);
dy4D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);
}
assert(dy4D.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ` +
`${dy4D.rank}.`);
assert(input4D.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ` +
`${input4D.rank}.`);
const inputs = { dy: dy4D, input: input4D };
const attrs = { filterSize, strides, pad };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(AvgPoolGrad, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPoolGrad = op({ avgPoolGrad_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const avgPoolGradConfig = {
kernelName: AvgPool,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { filterSize, strides, pad } = attrs;
return { x: () => avgPoolGrad(dy, x, filterSize, strides, pad) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the dot product of two matrices, A * B. These must be matrices.
*
* ```js
* const a = tf.tensor2d([1, 2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.matMul(b).print(); // or tf.matMul(a, b)
* ```
* @param a First matrix in dot product operation.
* @param b Second matrix in dot product operation.
* @param transposeA If true, `a` is transposed before multiplication.
* @param transposeB If true, `b` is transposed before multiplication.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function matMul_(a, b, transposeA = false, transposeB = false) {
let $a = convertToTensor(a, 'a', 'matMul');
let $b = convertToTensor(b, 'b', 'matMul');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
const attrs = { transposeA, transposeB };
return ENGINE.runKernel(BatchMatMul, inputs, attrs);
}
const matMul = op({ matMul_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const batchMatMulGradConfig = {
kernelName: BatchMatMul,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved, attrs) => {
const [a, b] = saved;
const { transposeA, transposeB } = attrs;
if (!transposeA && !transposeB) {
return {
a: () => matMul(dy, b, false, true),
b: () => matMul(a, dy, true, false)
};
}
else if (!transposeA && transposeB) {
return {
a: () => matMul(dy, b, false, false),
b: () => matMul(dy, a, true, false)
};
}
else if (transposeA && !transposeB) {
return {
a: () => matMul(b, dy, false, true),
b: () => matMul(a, dy, false, false)
};
}
else {
return {
a: () => matMul(b, dy, true, true),
b: () => matMul(dy, a, true, true)
};
}
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* This operation divides "spatial" dimensions `[1, ..., M]` of the input into
* a grid of blocks of shape `blockShape`, and interleaves these blocks with
* the "batch" dimension (0) such that in the output, the spatial
* dimensions `[1, ..., M]` correspond to the position within the grid,
* and the batch dimension combines both the position within a spatial block
* and the original batch position. Prior to division into blocks,
* the spatial dimensions of the input are optionally zero padded
* according to `paddings`. See below for a precise description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
* const blockShape = [2, 2];
* const paddings = [[0, 0], [0, 0]];
*
* x.spaceToBatchND(blockShape, paddings).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=
* 0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad
* from input dimension `i + 1`, which corresponds to spatial dimension `i`. It
* is required that
* `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`
*
* This operation is equivalent to the following steps:
*
* 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input
* according to `paddings` to produce `padded` of shape paddedShape.
*
* 2. Reshape `padded` to `reshapedPadded` of shape:
* `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,
* paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`
*
* 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`
* of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the
* batch dimension, producing an output tensor of shape:
* `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,
* paddedShape[M] / blockShape[M-1]] + remainingShape`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function spaceToBatchND_(x, blockShape, paddings) {
const $x = convertToTensor(x, 'x', 'spaceToBatchND');
assert($x.rank >= 1 + blockShape.length, () => `input rank ${$x.rank} should be > than [blockShape] ${blockShape.length}`);
assert(paddings.length === blockShape.length, () => `paddings.shape[0] ${paddings.length} must be equal to [blockShape] ${blockShape.length}`);
assert($x.shape.reduce((a, b, i) => {
if (i > 0 && i <= blockShape.length) {
return a &&
((b + paddings[i - 1][0] + paddings[i - 1][1]) %
blockShape[i - 1] ===
0);
}
return a;
}, true), () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${paddings.toString()} must be divisible by blockShapes ${blockShape.toString()}`);
const inputs = { x: $x };
const attrs = { blockShape, paddings };
return ENGINE.runKernel(SpaceToBatchND, inputs, attrs);
}
const spaceToBatchND = op({ spaceToBatchND_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const batchToSpaceNDGradConfig = {
kernelName: BatchToSpaceND,
gradFunc: (dy, saved, attrs) => {
const { blockShape, crops } = attrs;
return { x: () => spaceToBatchND(dy, blockShape, crops) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const broadcastToGradConfig = {
kernelName: BroadcastTo,
gradFunc: (dy, saved, attrs) => {
const broadCastToAttrs = attrs;
const inputShape = broadCastToAttrs.inputShape;
const outputShape = broadCastToAttrs.shape;
const reps = Array.from(outputShape);
for (let i = inputShape.length - 1; i >= 0; i--) {
if (inputShape[i] === outputShape[i]) {
reps[i] = 1;
}
else if (inputShape[i] !== 1) {
throw new Error(`broadcastTo(): [${inputShape}] cannot be broadcast to [${outputShape}].`);
}
}
const axes = [];
for (let i = 0; i < reps.length; i++) {
if (reps[i] > 1) {
axes.push(i);
}
}
return { x: () => sum$1(dy, axes, true /* keepDims */) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const castGradConfig = {
kernelName: Cast,
gradFunc: (dy) => {
return { x: () => dy.clone() };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const ceilGradConfig = {
kernelName: Ceil,
gradFunc: (dy) => {
// TODO(manrajgrover): Return null for gradients when backprop supports it.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a >= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greaterEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greaterEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'greaterEqual', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'greaterEqual', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(GreaterEqual, inputs);
}
const greaterEqual = op({ greaterEqual_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a <= b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.lessEqual(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function lessEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'lessEqual', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'lessEqual', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LessEqual, inputs);
}
const lessEqual = op({ lessEqual_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of `a AND b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalAnd(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalAnd_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');
const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LogicalAnd, inputs);
}
const logicalAnd = op({ logicalAnd_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a new tensor with the same values and shape as the specified
* tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
*
* x.clone().print();
* ```
*
* @param x The tensor to clone.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function clone_(x) {
const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');
const inputs = { x: $x };
// Note this op is called tf.identity in python. Hence the kernel name used
// here.
return ENGINE.runKernel(Identity, inputs);
}
const clone = op({ clone_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Broadcast an array to a compatible shape NumPy-style.
*
* The tensor's shape is compared to the broadcast shape from end to beginning.
* Ones are prepended to the tensor's shape until is has the same length as
* the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is
* already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then
* the input tensor is tiled N times along that axis (using tf.tile).
*
* @param input The tensor that is to be broadcasted.
* @param shape The input is to be broadcast to this shape.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function broadcastTo_(x, shape) {
let input = convertToTensor(x, 'broadcastTo', 'x');
const xShape = input.shape;
if (shape.some(d => !(d > 0) || d % 1 !== 0)) {
throw new Error(`broadcastTo(): Invalid broadcast shape [${shape}].`);
}
if (shape.length < input.rank) {
throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${input.rank}.`);
}
if (shape.length > input.rank) {
const newShape = input.shape.slice();
while (newShape.length < shape.length) {
newShape.unshift(1);
}
input = reshape(input, newShape);
}
const inputShape = input.shape;
const reps = Array.from(shape);
for (let i = shape.length - 1; i >= 0; i--) {
if (inputShape[i] === shape[i]) {
reps[i] = 1;
}
else if (input.shape[i] !== 1) {
throw new Error(`broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);
}
}
const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);
if (axes.length === 0) {
return clone(input);
}
// TODO call broadcastTo kernel directly once backends implement broadcstTo
const inputs = { x: input };
const attrs = { reps };
return ENGINE.runKernel(Tile, inputs, attrs);
}
const broadcastTo = op({ broadcastTo_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the elements, either `a` or `b` depending on the `condition`.
*
* If the condition is true, select from `a`, otherwise select from `b`.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const a = tf.tensor1d([1 , 2, 3]);
* const b = tf.tensor1d([-1, -2, -3]);
*
* a.where(cond, b).print();
* ```
*
* @param condition The input condition. Must be of dtype bool.
* @param a If `condition` is rank 1, `a` may have a higher rank but
* its first dimension must match the size of `condition`.
* @param b A tensor with the same dtype as `a` and with shape that is
* compatible with `a`.
* @return A tensor with same dtype as `a` and `b`, and shape that is
* broadcastable from `a` and `b`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function where_(condition, a, b) {
const $a = convertToTensor(a, 'a', 'where');
const $b = convertToTensor(b, 'b', 'where');
const $condition = convertToTensor(condition, 'condition', 'where', 'bool');
// TODO: move this logic to forward function when the broadcastTo op is
// implemented in WASM.
// Find the broadcastable shape for $condition, $a, and $b.
const broadcastShape = assertAndGetBroadcastShape(assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);
const $broadcastedCondition = broadcastTo($condition, broadcastShape);
const $broadcastedA = broadcastTo($a, broadcastShape);
const $broadcastedB = broadcastTo($b, broadcastShape);
const inputs = {
condition: $broadcastedCondition,
t: $broadcastedA,
e: $broadcastedB
};
return ENGINE.runKernel(Select, inputs);
}
const where = op({ where_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const clipByValueGradConfig = {
kernelName: ClipByValue,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { clipValueMin, clipValueMax } = attrs;
return {
x: () => where(logicalAnd(greaterEqual(x, clipValueMin), lessEqual(x, clipValueMax)), dy, zerosLike(dy)),
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const complexAbsGradConfig = {
kernelName: ComplexAbs,
inputsToSave: ['x'],
gradFunc: absGradConfig.gradFunc,
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Splits a `tf.Tensor` into sub tensors.
*
* If `numOrSizeSplits` is a number, splits `x` along dimension `axis`
* into `numOrSizeSplits` smaller tensors.
* Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.
*
* If `numOrSizeSplits` is a number array, splits `x` into
* `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the
* same size as `x` except along dimension `axis` where the size is
* `numOrSizeSplits[i]`.
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);
* const [a, b] = tf.split(x, 2, 1);
* a.print();
* b.print();
*
* const [c, d, e] = tf.split(x, [1, 2, 1], 1);
* c.print();
* d.print();
* e.print();
* ```
*
* @param x The input tensor to split.
* @param numOrSizeSplits Either an integer indicating the number of
* splits along the axis or an array of integers containing the sizes of
* each output tensor along the axis. If a number then it must evenly divide
* `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.
* Can contain one -1 indicating that dimension is to be inferred.
* @param axis The dimension along which to split. Defaults to 0 (the first
* dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function split_(x, numOrSizeSplits, axis = 0) {
const $x = convertToTensor(x, 'x', 'split');
const inputs = { x: $x };
const attr = { numOrSizeSplits, axis };
return ENGINE.runKernel(SplitV, inputs, attr);
}
const split = op({ split_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const concatGradConfig = {
kernelName: Concat,
saveAllInputs: true,
gradFunc: (dy, saved, attrs) => {
const shapes = saved.map(t => t.shape);
const { axis } = attrs;
const $axis = parseAxisParam(axis, saved[0].shape)[0];
const sizeSplits = shapes.map(s => s[$axis]);
const derTensors = split(dy, sizeSplits, $axis);
return derTensors.map(t => () => t);
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 2D convolution.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.
* @param dy The dy image, of rank 4 or rank 3, of shape
* [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.
* @param filterShape The shape of the filter, length 4,
* [filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropFilter_(x, dy, filterShape, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +
`${x4D.shape}.`);
assert(dy4D.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +
`${dy4D.shape}.`);
assert(filterShape.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +
`${filterShape}.`);
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
assert(inDepth === filterShape[2], () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +
`match input depth in filter (${filterShape[2]}.`);
assert(outDepth === filterShape[3], () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +
`match output depth for filter (${filterShape[3]}).`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2dDerFilter: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dataFormat, dimRoundingMode, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Conv2DBackpropFilter, inputs, attrs);
}
const conv2DBackpropFilter = op({ conv2DBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 2D convolution.
*
* @param xShape The shape of the input: [batch, height, width, inDepth].
* If length of 3, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 4 or rank 3 of shape
* `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function conv2DBackpropInput_(xShape, dy, filter, strides, pad, dataFormat = 'NHWC', dimRoundingMode) {
assert(xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape4D = xShape;
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
xShape4D = [1, xShape[0], xShape[1], xShape[2]];
}
assert(xShape4D.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ` +
`${xShape4D.length}.`);
assert(dy4D.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got ` +
`rank ${dy4D.rank}`);
assert(filter.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got ` +
`rank ${filter.rank}`);
const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];
const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];
assert(inDepth === filter.shape[2], () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[2]}.`);
assert(outDepth === filter.shape[3], () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[3]}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2dDerInput: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv2DBackpropInput, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2DBackpropInput = op({ conv2DBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
*
* @param inputShape Input tensor shape is of the following dimensions:
* `[batch, height, width, inChannels]`.
* @param filterShape The filter shape is of the following dimensions:
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat The data format of the input and output data.
* Defaults to 'NHWC'.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.
* Defaults to `[1, 1]`. If `dilations` is a single number, then
* `dilationHeight == dilationWidth`.
*/
function computeDilation2DInfo(inputShape, filterShape, strides, pad, dataFormat = 'NHWC', dilations) {
// `computerConv2DInfo` require filterShape to be in the dimension of:
// `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have
// outDepth, it should have the same depth as the input.
// Input shape: [batch, height, width, inChannels]
const inputChannels = inputShape[3];
const $filterShape = [...filterShape, inputChannels];
const $dataFormat = convertConv2DDataFormat(dataFormat);
return computeConv2DInfo(inputShape, $filterShape, strides, dilations, pad, null /* roundingMode */, null /* depthWise */, $dataFormat);
}
function computePool2DInfo(inShape, filterSize, strides, dilations, pad, roundingMode, dataFormat = 'channelsLast') {
const [filterHeight, filterWidth] = parseTupleParam(filterSize);
let filterShape;
if (dataFormat === 'channelsLast') {
filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];
}
else if (dataFormat === 'channelsFirst') {
filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, false, dataFormat);
}
/**
* Computes the information for a forward pass of a pooling3D operation.
*/
function computePool3DInfo(inShape, filterSize, strides, dilations, pad, roundingMode, dataFormat = 'NDHWC') {
const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);
let filterShape;
let $dataFormat;
if (dataFormat === 'NDHWC') {
$dataFormat = 'channelsLast';
filterShape =
[filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];
}
else if (dataFormat === 'NCDHW') {
$dataFormat = 'channelsFirst';
filterShape =
[filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
return computeConv3DInfo(inShape, filterShape, strides, dilations, pad, false, $dataFormat, roundingMode);
}
/**
* Computes the information for a forward pass of a convolution/pooling
* operation.
*/
function computeConv2DInfo(inShape, filterShape, strides, dilations, pad, roundingMode, depthwise = false, dataFormat = 'channelsLast') {
let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];
if (dataFormat === 'channelsLast') {
[batchSize, inHeight, inWidth, inChannels] = inShape;
}
else if (dataFormat === 'channelsFirst') {
[batchSize, inChannels, inHeight, inWidth] = inShape;
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideHeight, strideWidth] = parseTupleParam(strides);
const [dilationHeight, dilationWidth] = parseTupleParam(dilations);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outHeight, outWidth } = getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight, effectiveFilterWidth, roundingMode, dataFormat);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === 'channelsFirst') {
outShape = [batchSize, outChannels, outHeight, outWidth];
}
else if (dataFormat === 'channelsLast') {
outShape = [batchSize, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inHeight,
inWidth,
inChannels,
outHeight,
outWidth,
outChannels,
padInfo,
strideHeight,
strideWidth,
filterHeight,
filterWidth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape
};
}
/**
* Computes the information for a forward pass of a 3D convolution/pooling
* operation.
*/
function computeConv3DInfo(inShape, filterShape, strides, dilations, pad, depthwise = false, dataFormat = 'channelsLast', roundingMode) {
let [batchSize, inDepth, inHeight, inWidth, inChannels] = [-1, -1, -1, -1, -1];
if (dataFormat === 'channelsLast') {
[batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;
}
else if (dataFormat === 'channelsFirst') {
[batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
const [filterDepth, filterHeight, filterWidth, , filterChannels] = filterShape;
const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);
const [dilationDepth, dilationHeight, dilationWidth] = parse3TupleParam(dilations);
const effectiveFilterDepth = getEffectiveFilterSize(filterDepth, dilationDepth);
const effectiveFilterHeight = getEffectiveFilterSize(filterHeight, dilationHeight);
const effectiveFilterWidth = getEffectiveFilterSize(filterWidth, dilationWidth);
const { padInfo, outDepth, outHeight, outWidth } = get3DPadAndOutInfo(pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth, roundingMode);
const outChannels = depthwise ? filterChannels * inChannels : filterChannels;
let outShape;
if (dataFormat === 'channelsFirst') {
outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];
}
else if (dataFormat === 'channelsLast') {
outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];
}
return {
batchSize,
dataFormat,
inDepth,
inHeight,
inWidth,
inChannels,
outDepth,
outHeight,
outWidth,
outChannels,
padInfo,
strideDepth,
strideHeight,
strideWidth,
filterDepth,
filterHeight,
filterWidth,
effectiveFilterDepth,
effectiveFilterHeight,
effectiveFilterWidth,
dilationDepth,
dilationHeight,
dilationWidth,
inShape,
outShape,
filterShape
};
}
function computeOutputShape2D(inShape, fieldSize, stride, zeroPad, roundingMode) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputRows = inShape[0];
const inputCols = inShape[1];
const outputRows = round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputCols = round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
return [outputRows, outputCols];
}
function computeOutputShape4D(inShape, fieldSize, outChannels, stride, zeroPad, roundingMode) {
if (zeroPad == null) {
zeroPad = computeDefaultPad(inShape, fieldSize, stride);
}
const inputDepth = inShape[0];
const inputRows = inShape[1];
const inputCols = inShape[2];
const outputDepths = round((inputDepth - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputRows = round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
const outputCols = round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);
return [outputDepths, outputRows, outputCols, outChannels];
}
function computeDefaultPad(inputShape, fieldSize, stride, dilation = 1) {
const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);
return Math.floor((inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);
}
function parseTupleParam(param) {
if (typeof param === 'number') {
return [param, param, param];
}
if (param.length === 2) {
return [param[0], param[1], 1];
}
return param;
}
function parse3TupleParam(param) {
return typeof param === 'number' ? [param, param, param] : param;
}
/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d
* Atrous convolution is equivalent to standard convolution with upsampled
* filters with effective_filter_height =
* filter_height + (filter_height - 1) * (dilation - 1)
* and effective_filter_width =
* filter_width + (filter_width - 1) * (dilation - 1),
* produced by inserting dilation - 1 zeros along consecutive elements across
* the filters' spatial dimensions.
* When there is a dilation, this converts a filter dimension to the
* effective filter dimension, so it can be used in a standard convolution.
*/
function getEffectiveFilterSize(filterSize, dilation) {
if (dilation <= 1) {
return filterSize;
}
return filterSize + (filterSize - 1) * (dilation - 1);
}
function getPadAndOutInfo(pad, inHeight, inWidth, strideHeight, strideWidth, filterHeight, filterWidth, roundingMode, dataFormat) {
let padInfo;
let outHeight;
let outWidth;
if (typeof pad === 'number') {
const padType = (pad === 0) ? 'VALID' : 'NUMBER';
padInfo = { top: pad, bottom: pad, left: pad, right: pad, type: padType };
const outShape = computeOutputShape2D([inHeight, inWidth], filterHeight, strideHeight, pad, roundingMode);
outHeight = outShape[0];
outWidth = outShape[1];
}
else if (pad === 'same') {
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongHeight = Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);
const padAlongWidth = Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, type: 'SAME' };
}
else if (pad === 'valid') {
padInfo = { top: 0, bottom: 0, left: 0, right: 0, type: 'VALID' };
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
}
else if (typeof pad === 'object') {
const top = dataFormat === 'channelsLast' ? pad[1][0] : pad[2][0];
const bottom = dataFormat === 'channelsLast' ? pad[1][1] : pad[2][1];
const left = dataFormat === 'channelsLast' ? pad[2][0] : pad[3][0];
const right = dataFormat === 'channelsLast' ? pad[2][1] : pad[3][1];
const padType = (top === 0 && bottom === 0 && left === 0 && right === 0) ?
'VALID' :
'EXPLICIT';
padInfo = { top, bottom, left, right, type: padType };
outHeight = round((inHeight - filterHeight + top + bottom) / strideHeight + 1, roundingMode);
outWidth = round((inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);
}
else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outHeight, outWidth };
}
function get3DPadAndOutInfo(pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth, filterDepth, filterHeight, filterWidth, roundingMode) {
let padInfo;
let outDepth;
let outHeight;
let outWidth;
if (typeof pad === 'number') {
const padType = (pad === 0) ? 'VALID' : 'NUMBER';
padInfo = {
top: pad,
bottom: pad,
left: pad,
right: pad,
front: pad,
back: pad,
type: padType
};
const outShape = computeOutputShape4D([inDepth, inHeight, inWidth, 1], filterDepth, 1, strideDepth, pad, roundingMode);
outDepth = outShape[0];
outHeight = outShape[1];
outWidth = outShape[2];
}
else if (pad === 'same') {
outDepth = Math.ceil(inDepth / strideDepth);
outHeight = Math.ceil(inHeight / strideHeight);
outWidth = Math.ceil(inWidth / strideWidth);
const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;
const padAlongHeight = (outHeight - 1) * strideHeight + filterHeight - inHeight;
const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;
const front = Math.floor(padAlongDepth / 2);
const back = padAlongDepth - front;
const top = Math.floor(padAlongHeight / 2);
const bottom = padAlongHeight - top;
const left = Math.floor(padAlongWidth / 2);
const right = padAlongWidth - left;
padInfo = { top, bottom, left, right, front, back, type: 'SAME' };
}
else if (pad === 'valid') {
padInfo = {
top: 0,
bottom: 0,
left: 0,
right: 0,
front: 0,
back: 0,
type: 'VALID'
};
outDepth = Math.ceil((inDepth - filterDepth + 1) / strideDepth);
outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);
outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);
}
else {
throw Error(`Unknown padding parameter: ${pad}`);
}
return { padInfo, outDepth, outHeight, outWidth };
}
/**
* Rounds a value depending on the rounding mode
* @param value
* @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function round(value, roundingMode) {
if (!roundingMode) {
return Math.trunc(value);
}
switch (roundingMode) {
case 'round':
// used for Caffe Conv
return Math.round(value);
case 'ceil':
// used for Caffe Pool
return Math.ceil(value);
case 'floor':
return Math.floor(value);
default:
throw new Error(`Unknown roundingMode ${roundingMode}`);
}
}
function tupleValuesAreOne(param) {
const [dimA, dimB, dimC] = parseTupleParam(param);
return dimA === 1 && dimB === 1 && dimC === 1;
}
function eitherStridesOrDilationsAreOne(strides, dilations) {
return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);
}
/**
* Convert Conv2D dataFormat from 'NHWC'|'NCHW' to
* 'channelsLast'|'channelsFirst'
* @param dataFormat in 'NHWC'|'NCHW' mode
* @return dataFormat in 'channelsLast'|'channelsFirst' mode
* @throws unknown dataFormat
*/
function convertConv2DDataFormat(dataFormat) {
if (dataFormat === 'NHWC') {
return 'channelsLast';
}
else if (dataFormat === 'NCHW') {
return 'channelsFirst';
}
else {
throw new Error(`Unknown dataFormat ${dataFormat}`);
}
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const conv2DGradConfig = {
kernelName: Conv2D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const [x4D, $filter] = saved;
const { dilations, strides, pad, dataFormat } = attrs;
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of conv2D: dilation rates greater than 1 ' +
`are not yet supported in gradients. Got dilations '${dilations}'`);
return {
x: () => conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad, dataFormat),
filter: () => conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad, dataFormat)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv2d');
const $filter = convertToTensor(filter, 'filter', 'conv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];
assert(inDepth === $filter.shape[2], () => `Error in conv2d: depth of input (${inDepth}) must match ` +
`input depth for filter ${$filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv2D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv2D, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const conv2d = op({ conv2d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const conv2DBackpropInputGradConfig = {
kernelName: Conv2DBackpropInput,
inputsToSave: ['dy', 'filter'],
gradFunc: (ddx, saved, attrs) => {
const [dy, filter] = saved;
const { strides, pad, dataFormat, dimRoundingMode } = attrs;
return {
dy: () => conv2d(ddx, filter, strides, pad, dataFormat, 1 /* dilations */, dimRoundingMode),
filter: () => conv2DBackpropFilter(ddx, dy, filter.shape, strides, pad, dataFormat, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the derivative of the filter of a 3D convolution.
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* [batch, depth, height, width, inChannels]. If rank 4, batch of 1 is
* assumed.
* @param dy The dy image, of rank 5 or rank 4, of shape
* [batch, depth, height, width, outDepth]. If rank 4, batch of 1 is
* assumed.
* @param filterShape The shape of the filter, length 5,
* [filterDepth, filterHeight, filterWidth, inDepth, outDepth].
* @param strides The strides of the convolution: [strideDepth, strideHeight,
* strideWidth].
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
*/
function conv3DBackpropFilter_(x, dy, filterShape, strides, pad) {
let x5D = x;
if (x.rank === 4) {
x5D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);
}
let dy5D = dy;
if (dy5D.rank === 4) {
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ` +
`${x5D.shape}.`);
assert(dy5D.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ` +
`${dy5D.shape}.`);
assert(filterShape.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ` +
`${filterShape}.`);
assert(x5D.shape[4] === filterShape[3], () => `Error in conv3dDerFilter: depth of input ${x5D.shape[4]}) must ` +
`match input depth in filter (${filterShape[3]}.`);
assert(dy5D.shape[4] === filterShape[4], () => `Error in conv3dDerFilter: depth of dy (${dy5D.shape[4]}) must ` +
`match output depth for filter (${filterShape[4]}).`);
const inputs = { x: x5D, dy: dy5D };
const attrs = { strides, pad, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Conv3DBackpropFilterV2, inputs, attrs);
}
const conv3DBackpropFilter = op({ conv3DBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the derivative of the input of a 3D convolution.
*
* @param xShape The shape of the input: [batch, depth, height, width,
* in_channels]. If length of 4, batch of 1 is assumed.
* @param dy The derivative of the output, of rank 5 or rank 4 of shape
* `[batch, outDepth, outHeight, outWidth, in_channels]`.
* If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm used:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
*/
function conv3DBackpropInput_(xShape, dy, filter, strides, pad) {
assert(xShape.length === dy.rank, () => `Length of inShape ` +
`(${xShape.length}) and rank of dy (${dy.rank}) must match`);
let xShape5D = xShape;
let dy5D = dy;
let reshapedTo5D = false;
if (dy.rank === 4) {
reshapedTo5D = true;
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
}
const inDepth = xShape5D[4];
const outDepth = dy5D.shape[4];
assert(xShape5D.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ` +
`${xShape5D.length}.`);
assert(dy5D.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got ` +
`rank ${dy5D.rank}`);
assert(filter.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got ` +
`rank ${filter.rank}`);
assert(inDepth === filter.shape[3], () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +
`match input depth for filter ${filter.shape[3]}.`);
assert(outDepth === filter.shape[4], () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +
`match output depth for filter ${filter.shape[4]}.`);
const inputs = { dy: dy5D, filter };
const attrs = { pad, strides, inputShape: xShape5D };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3DBackpropInput = op({ conv3DBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const conv3DGradConfig = {
kernelName: Conv3D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad } = attrs;
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of conv3D: dilation rates greater than 1 are ' +
`not yet supported in gradients. Got dilations '${dilations}'`);
const [x5D, $filter] = saved;
return {
x: () => conv3DBackpropInput(x5D.shape, dy, $filter, strides, pad),
filter: () => conv3DBackpropFilter(x5D, dy, $filter.shape, strides, pad)
};
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes sin of the input Tensor element-wise: `sin(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.sin().print(); // or tf.sin(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sin_(x) {
const $x = convertToTensor(x, 'x', 'sin');
const inputs = { x: $x };
return ENGINE.runKernel(Sin, inputs);
}
const sin = op({ sin_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const cosGradConfig = {
kernelName: Cos,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(neg(sin(cast(x, 'float32'))), dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.sinh().print(); // or tf.sinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sinh_(x) {
const $x = convertToTensor(x, 'x', 'sinh');
const inputs = { x: $x };
return ENGINE.runKernel(Sinh, inputs);
}
const sinh = op({ sinh_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const coshGradConfig = {
kernelName: Cosh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(sinh(cast(x, 'float32')), dy) };
}
};
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
/**
* Returns true if the axis specifies the inner most dimensions of the
* array.
*/
function axesAreInnerMostDims(axes, rank) {
for (let i = 0; i < axes.length; ++i) {
if (axes[axes.length - i - 1] !== rank - 1 - i) {
return false;
}
}
return true;
}
function combineLocations(outputLoc, reduceLoc, axes) {
const rank = outputLoc.length + reduceLoc.length;
const loc = [];
let outIdx = 0;
let reduceIdx = 0;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
loc.push(outputLoc[outIdx++]);
}
else {
loc.push(reduceLoc[reduceIdx++]);
}
}
return loc;
}
function computeOutAndReduceShapes(aShape, axes) {
const outShape = [];
const rank = aShape.length;
for (let dim = 0; dim < rank; dim++) {
if (axes.indexOf(dim) === -1) {
outShape.push(aShape[dim]);
}
}
const reduceShape = axes.map(dim => aShape[dim]);
return [outShape, reduceShape];
}
function expandShapeToKeepDim(shape, axes) {
const reduceSubShape = axes.map(x => 1);
return combineLocations(shape, reduceSubShape, axes);
}
function assertAxesAreInnerMostDims(msg, axes, rank) {
assert(axesAreInnerMostDims(axes, rank), () => `${msg} supports only inner-most axes for now. ` +
`Got axes ${axes} and rank-${rank} input.`);
}
/**
* Returns the axes permutation to be used with `tf.transpose`, if such
* permutation is necessary. Otherwise it returns null. This method is used by
* operations that operate only on inner-most axes.
*/
function getAxesPermutation(axes, rank) {
if (axesAreInnerMostDims(axes, rank)) {
return null;
}
const result = [];
for (let i = 0; i < rank; ++i) {
if (axes.indexOf(i) === -1) {
result.push(i);
}
}
axes.forEach(axis => result.push(axis));
return result;
}
/** Returns the axes permutation that undoes the original permutation. */
function getUndoAxesPermutation(axes) {
return axes.map((axis, i) => [i, axis])
.sort((a, b) => a[1] - b[1])
.map(x => x[0]);
}
function getInnerMostAxes(numAxes, rank) {
const res = [];
for (let i = rank - numAxes; i < rank; ++i) {
res.push(i);
}
return res;
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the cumulative sum of a `tf.Tensor` along `axis`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4]);
* x.cumsum().print();
* ```
* ```js
* const x = tf.tensor([[1, 2], [3, 4]]);
* x.cumsum().print();
* ```
*
* @param x The input tensor to be summed.
* @param axis The axis along which to sum. Optional. Defaults to 0.
* @param exclusive Whether to perform exclusive cumulative sum. Optional.
* Defaults to false. If set to true then the sum of each tensor entry
* does not include its own value, but only the values previous to it
* along the specified axis.
* @param reverse Whether to sum in the opposite direction. Optional.
* Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Scan'}
*/
function cumsum_(x, axis = 0, exclusive = false, reverse = false) {
const $x = convertToTensor(x, 'x', 'cumsum');
const inputs = { x: $x };
const attrs = { axis, exclusive, reverse };
return ENGINE.runKernel(Cumsum, inputs, attrs);
}
const cumsum = op({ cumsum_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.
*
* The returned `tf.Tensor`'s dimension `i` will correspond to the input
* dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,
* where `n` is the rank of the input `tf.Tensor`. Hence by default, this
* operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);
*
* a.transpose().print(); // or tf.transpose(a)
* ```
*
* @param x The tensor to transpose.
* @param perm The permutation of the dimensions of a.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function transpose_(x, perm) {
const $x = convertToTensor(x, 'x', 'transpose');
if (perm == null) {
perm = $x.shape.map((s, i) => i).reverse();
}
assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of perm ${perm}.`);
perm.forEach(axis => {
assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +
` but got ${perm}`);
});
if ($x.rank <= 1) {
return $x.clone();
}
const inputs = { x: $x };
const attrs = { perm };
return ENGINE.runKernel(Transpose, inputs, attrs);
}
const transpose = op({ transpose_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const cumsumGradConfig = {
kernelName: Cumsum,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { axis, exclusive, reverse } = attrs;
return {
x: () => {
const permutation = getAxesPermutation([axis], x.rank);
let out = cumsum(dy, axis, exclusive, !reverse);
if (permutation != null) {
out = transpose(out, permutation);
}
return out;
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad, dilations = [1, 1], dimRoundingMode) {
let x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
let dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { x: x4D, dy: dy4D };
const attrs = { strides, pad, dimRoundingMode, dilations, filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
}
const depthwiseConv2dNativeBackpropFilter = op({ depthwiseConv2dNativeBackpropFilter_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function depthwiseConv2dNativeBackpropInput_(xShape, dy, filter, strides, pad, dilations = [1, 1], dimRoundingMode) {
let dy4D = dy;
let reshapedTo4D = false;
if (dy.rank === 3) {
reshapedTo4D = true;
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
const inputs = { dy: dy4D, filter };
const attrs = { strides, pad, dimRoundingMode, dilations, inputShape: xShape };
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(DepthwiseConv2dNativeBackpropInput, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2dNativeBackpropInput = op({ depthwiseConv2dNativeBackpropInput_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const depthwiseConv2dNativeGradConfig = {
kernelName: DepthwiseConv2dNative,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const { dilations, strides, pad, dimRoundingMode } = attrs;
const $dilations = dilations == null ? [1, 1] : dilations;
assert(tupleValuesAreOne($dilations), () => 'Error in gradient of depthwiseConv2dNative: dilation rates ' +
`greater than 1 are not yet supported. Got dilations ` +
`'${$dilations}'`);
const [x, filter] = saved;
assert(x.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be ` +
`rank 4, but got rank ${x.rank}.`);
assert(filter.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be ` +
`rank 4, but got rank ${filter.rank}.`);
assert(x.shape[3] === filter.shape[2], () => `Error in gradient of depthwiseConv2d: number of input ` +
`channels (${x.shape[3]}) must match the inChannels dimension ` +
`in filter ${filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, $dilations), () => 'Error in gradient of depthwiseConv2d: Either strides or ' +
`dilations must be 1. Got strides ${strides} and dilations ` +
`'${$dilations}'.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
return {
x: () => depthwiseConv2dNativeBackpropInput(x.shape, dy, filter, strides, pad, $dilations, dimRoundingMode),
filter: () => depthwiseConv2dNativeBackpropFilter(x, dy, filter.shape, strides, pad, $dilations, dimRoundingMode),
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const dilation2dGradConfig = {
kernelName: Dilation2D,
inputsToSave: ['x', 'filter'],
gradFunc: (dy, saved, attrs) => {
const [x, filter] = saved;
const inputInputs = { x, filter, dy };
const filterInputs = { x, filter, dy };
return {
x: () => ENGINE.runKernel(Dilation2DBackpropInput, inputInputs, attrs),
filter: () => ENGINE.runKernel(Dilation2DBackpropFilter, filterInputs, attrs)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const eluGradConfig = {
kernelName: Elu,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
const inputs = { dy, y };
return { x: () => ENGINE.runKernel(EluGrad, inputs) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.exp().print(); // or tf.exp(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function exp_(x) {
const $x = convertToTensor(x, 'x', 'exp');
const inputs = { x: $x };
return ENGINE.runKernel(Exp, inputs);
}
const exp = op({ exp_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const erfGradConfig = {
kernelName: Erf,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
const a = mul(exp(neg(square(x))), 2 / Math.sqrt(Math.PI));
return { x: () => mul(dy, a) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const expGradConfig = {
kernelName: Exp,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(dy, y) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const expandDimsGradConfig = {
kernelName: ExpandDims,
inputsToSave: ['input'],
gradFunc: (dy, saved) => {
const [input] = saved;
return { input: () => reshape(dy, input.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const expm1GradConfig = {
kernelName: Expm1,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, exp(x)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const floorGradConfig = {
kernelName: Floor,
gradFunc: (dy) => {
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const floorDivGradConfig = {
kernelName: FloorDiv,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = div(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
let res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = reshape(sum$1(res, reduceAxes), b.shape);
}
const tmp = square(b);
return neg(div(res, cast(tmp, 'float32')));
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes reciprocal of square root of the input `tf.Tensor` element-wise:
* `y = 1 / sqrt(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, 4, -1]);
*
* x.rsqrt().print(); // or tf.rsqrt(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function rsqrt_(x) {
const $x = convertToTensor(x, 'x', 'rsqrt');
const inputs = { x: $x };
return ENGINE.runKernel(Rsqrt, inputs);
}
const rsqrt = op({ rsqrt_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Construct a tensor by repeating it the number of times given by reps.
*
* This operation creates a new tensor by replicating `input` `reps`
* times. The output tensor's i'th dimension has `input.shape[i] *
* reps[i]` elements, and the values of `input` are replicated
* `reps[i]` times along the i'th dimension. For example, tiling
* `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
*
* a.tile([2]).print(); // or a.tile([2])
* ```
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* a.tile([1, 2]).print(); // or a.tile([1, 2])
* ```
* @param x The tensor to tile.
* @param reps Determines the number of replications per dimension.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function tile_(x, reps) {
const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');
assert($x.rank === reps.length, () => `Error in transpose: rank of input ${$x.rank} ` +
`must match length of reps ${reps}.`);
const inputs = { x: $x };
const attrs = { reps };
return ENGINE.runKernel(Tile, inputs, attrs);
}
const tile = op({ tile_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const fusedBatchNormGradConfig = {
kernelName: FusedBatchNorm,
inputsToSave: ['x', 'mean', 'variance', 'scale'],
gradFunc: (dy, saved, attrs) => {
const { varianceEpsilon } = attrs;
const [x, mean, variance, scale] = saved;
const scaleValue = scale == null ? scalar(1) : scale;
const reductionAxes = getReductionAxes(mean.shape, x.shape);
const tileShape = [];
if (mean.rank === 1) {
for (let i = 0; i < x.shape.length - 1; ++i) {
tileShape.push(x.shape[i]);
}
tileShape.push(1);
}
const xMinusMean = sub(x, mean);
const dyTimesScaleValue = mul(dy, scaleValue);
const oneOverSqrtVariance = rsqrt(add$1(variance, scalar(varianceEpsilon)));
const minusHalfRCube = mul(mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance), scalar(-0.5));
const derX = () => {
if (mean.rank === 1) {
return reshape(mul(mul(dy, tile(reshape(oneOverSqrtVariance, [1, 1, 1, mean.shape[0]]), tileShape)), scaleValue), x.shape);
}
else {
return reshape(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);
}
};
const derMean = () => {
let meanDer = mul(mul(oneOverSqrtVariance, scalar(-1)), dyTimesScaleValue);
if (mean.rank === 1) {
meanDer = sum$1(meanDer, reductionAxes);
}
return reshape(meanDer, mean.shape);
};
const derVariance = () => {
let varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);
if (mean.rank === 1) {
varianceDer = sum$1(varianceDer, reductionAxes);
}
return reshape(varianceDer, mean.shape);
};
const derScale = () => {
const xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);
let scaleDer = mul(dy, xMinusMean2TimesRsqrt);
if (mean.rank === 1) {
scaleDer = sum$1(scaleDer, reductionAxes);
}
return reshape(scaleDer, mean.shape);
};
const derOffset = () => {
let offsetDer = dy;
if (mean.rank === 1) {
offsetDer = sum$1(offsetDer, reductionAxes);
}
return reshape(offsetDer, mean.shape);
};
return {
x: derX,
mean: derMean,
variance: derVariance,
scale: derScale,
offset: derOffset
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the sum along segments of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');
* const numSegments = 3;
*
* x.unsortedSegmentSum(segmentIds, numSegments).print()
* //or tf.unsortedSegmentSum(x, segmentIds, numSegments)
* ```
* @param x The `tf.Tensor` that will be summed along its segments.
* @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s
* dimension along the `axis`. Maps each element of `x` to a segment.
* @param numSegments The number of distinct `segmentIds`.
*
* @doc {heading: 'Operations', subheading: 'Segment'}
*/
function unsortedSegmentSum_(x, segmentIds, numSegments) {
const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');
const $segmentIds = convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');
assert(isInt(numSegments), () => 'numSegments must be of dtype int');
const inputs = { x: $x, segmentIds: $segmentIds };
const attrs = { numSegments };
return ENGINE.runKernel(UnsortedSegmentSum, inputs, attrs);
}
const unsortedSegmentSum = op({ unsortedSegmentSum_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const gatherGradConfig = {
kernelName: GatherV2,
inputsToSave: ['x', 'indices'],
gradFunc: (dy, saved, attrs) => {
const [x, indices] = saved;
const { axis } = attrs;
const parsedAxis = parseAxisParam(axis, x.shape)[0];
const derX = () => {
const paramsShape = x.shape;
const indicesSize = indices.size;
const outerShape = paramsShape.slice(0, parsedAxis);
const outerDims = outerShape.length;
const innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);
const innerDims = innerShape.length;
const outerAxesIndices = arrayRange(0, outerDims);
const innerAxesIndices = arrayRange(outerDims + 1, outerDims + 1 + innerDims);
const valuesShape = arrayConcat([outerShape, [indicesSize], innerShape]);
const values = reshape(dy, valuesShape);
const reshapedIndices = reshape(indices, [indicesSize]);
const transposeDims = arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);
const valuesTranspose = transpose(values, transposeDims);
let paramsGrad = unsortedSegmentSum(valuesTranspose, reshapedIndices, x.shape[parsedAxis]);
const invertTransposeDims = getUndoAxesPermutation(transposeDims);
paramsGrad = transpose(paramsGrad, invertTransposeDims);
return paramsGrad;
};
return { x: derX, indices: () => indices };
}
};
function arrayRange(start, stop) {
const result = [];
for (let i = start; i < stop; ++i) {
result.push(i);
}
return result;
}
function arrayConcat(arrays) {
const result = [];
for (let i = 0; i < arrays.length; ++i) {
for (let j = 0; j < arrays[i].length; ++j) {
result.push(arrays[i][j]);
}
}
return result;
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const greaterEqualGradConfig = {
kernelName: GreaterEqual,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
return { a: () => zerosLike(a), b: () => zerosLike(b) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const identityGradConfig = {
kernelName: Identity,
gradFunc: (dy) => {
return { x: () => cast(dy, 'float32') };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const isFiniteGradConfig = {
kernelName: IsFinite,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const isInfGradConfig = {
kernelName: IsInf,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const isNanGradConfig = {
kernelName: IsNan,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a > b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.greater(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function greater_(a, b) {
let $a = convertToTensor(a, 'a', 'greater', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'greater', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Greater, inputs);
}
const greater = op({ greater_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const leakyReluGradConfig = {
kernelName: LeakyRelu,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { alpha } = attrs;
const mask = greater(x, 0);
// Returns `gradients * (features > 0) + alpha * gradients * (features <=
// 0)`.
return { x: () => where(mask, dy, mul(dy, alpha)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const log1pGradConfig = {
kernelName: Log1p,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, add$1(x, 1)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const logGradConfig = {
kernelName: Log,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, cast(x, 'float32')) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const logSoftmaxGradConfig = {
kernelName: LogSoftmax,
inputsToSave: [],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [value] = saved;
const { axis } = attrs;
return {
logits: () => {
const keepDims = true;
const softmax = exp(value);
return sub(dy, mul(sum$1(dy, axis, keepDims), softmax));
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function localResponseNormalizationBackprop_(x, y, dy, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const inputs = { x, y, dy };
const attrs = { depthRadius, bias, alpha, beta };
return ENGINE.runKernel(LRNGrad, inputs, attrs);
}
const localResponseNormalizationBackprop = op({ localResponseNormalizationBackprop_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const lrnGradConfig = {
kernelName: LRN,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { depthRadius, bias, alpha, beta } = attrs;
return {
x: () => localResponseNormalizationBackprop(x, y, dy, depthRadius, bias, alpha, beta)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a == b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.equal(b).print();
* ```
*
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function equal_(a, b) {
let $a = convertToTensor(a, 'a', 'equal', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'equal', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Equal, inputs);
}
const equal = op({ equal_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Gradient helper function for the min and max operations.
*/
function gradForMinAndMax(dy, y, xOrig, origAxes) {
if (y.rank < xOrig.rank) {
y = reshape(y, expandShapeToKeepDim(y.shape, origAxes));
}
if (dy.rank < xOrig.rank) {
dy = reshape(dy, expandShapeToKeepDim(dy.shape, origAxes));
}
return {
x: () => {
const dx = mul(dy, cast(equal(xOrig, y), dy.dtype));
return dx;
}
};
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const maxGradConfig = {
kernelName: Max,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const maxAttrs = attrs;
const { reductionIndices } = maxAttrs;
const x = saved[0];
const y = saved[1];
const origAxes = parseAxisParam(reductionIndices, x.shape);
const maxGrad = gradForMinAndMax(dy, y, x, origAxes);
return {
x: () => {
return maxGrad['x']();
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a < b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([2, 2, 2]);
*
* a.less(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function less_(a, b) {
let $a = convertToTensor(a, 'a', 'less', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'less', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Less, inputs);
}
const less = op({ less_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const maximumGradConfig = {
kernelName: Maximum,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(greaterEqual(a, b), 'float32'));
const derB = () => mul(dy, cast(less(a, b), 'float32'));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the backprop of a 3d max pool.
*
* @param dy The dy error, of rank 5 of shape
* [batchSize, depth, height, width, channels].
* assumed.
* @param input The original input image, of rank 5 or rank 4 of shape
* [batchSize, depth, height, width, channels].
* @param output The original output image, of rank 5 of shape
* [batchSize, outDepth, outHeight, outWidth, channels].
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad A string from: 'same', 'valid'. The type of padding algorithm
* used in the forward prop of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPool3dGrad_(dy, input, output, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'maxPool3dGrad');
const $input = convertToTensor(input, 'input', 'maxPool3dGrad');
const $output = convertToTensor(output, 'output', 'maxPool3dGrad');
let dy5D = $dy;
let input5D = $input;
let output5D = $output;
let reshapedTo5D = false;
if ($input.rank === 4) {
reshapedTo5D = true;
dy5D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);
input5D = reshape($input, [
1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]
]);
output5D = reshape($output, [
1, $output.shape[0], $output.shape[1], $output.shape[2], $output.shape[3]
]);
}
assert(dy5D.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ` +
`${dy5D.rank}.`);
assert(input5D.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ` +
`${input5D.rank}.`);
assert(output5D.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ` +
`${output5D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool3dGrad: pad must be an integer when ` +
`using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: dy5D, input: input5D, output: output5D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool3DGrad, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3dGrad = op({ maxPool3dGrad_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const maxPool3DGradConfig = {
kernelName: MaxPool3D,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, pad, dimRoundingMode } = attrs;
return {
x: () => maxPool3dGrad(dy, x, y, filterSize, strides, pad, dimRoundingMode)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the backprop of a 2D max pool.
*
* @param dy The dy error, of rank 4 or rank 3 of shape
* [batchSize, height, width, channels]. If rank 3, batch of 1 is
* assumed.
* @param input The original input image, of rank 4, of shape
* [batchSize, height, width, channels].
* @param output The original output image, of rank 4, of shape
* [batchSize, outHeight, outWidth, channels].
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm used in the forward prop of the op.
* 'same', 'valid', for more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPoolGrad_(dy, input, output, filterSize, strides, pad, dimRoundingMode) {
const $dy = convertToTensor(dy, 'dy', 'maxPoolGrad');
const $input = convertToTensor(input, 'input', 'maxPoolGrad');
const $output = convertToTensor(output, 'output', 'maxPoolGrad');
assert($input.rank === $dy.rank, () => `Rank of input (${$input.rank}) does not match rank of dy ` +
`(${$dy.rank})`);
assert($dy.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ` +
`${$dy.rank}.`);
assert($input.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ` +
`${$input.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPoolGrad: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { dy: $dy, input: $input, output: $output };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(MaxPoolGrad, inputs, attrs);
}
const maxPoolGrad = op({ maxPoolGrad_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const maxPoolGradConfig = {
kernelName: MaxPool,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [x, y] = saved;
const { filterSize, strides, pad } = attrs;
return {
x: () => maxPoolGrad(dy, x, y, filterSize, strides, pad)
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts two real numbers to a complex number.
*
* Given a tensor `real` representing the real part of a complex number, and a
* tensor `imag` representing the imaginary part of a complex number, this
* operation returns complex numbers elementwise of the form [r0, i0, r1, i1],
* where r represents the real part and i represents the imag part.
*
* The input tensors real and imag must have the same shape.
*
* ```js
* const real = tf.tensor1d([2.25, 3.25]);
* const imag = tf.tensor1d([4.75, 5.75]);
* const complex = tf.complex(real, imag);
*
* complex.print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function complex_(real, imag) {
const $real = convertToTensor(real, 'real', 'complex');
const $imag = convertToTensor(imag, 'imag', 'complex');
assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +
`must match in call to tf.complex().`);
const inputs = { real: $real, imag: $imag };
return ENGINE.runKernel(Complex, inputs);
}
const complex = op({ complex_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 0.
*
* ```js
* tf.zeros([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Can
* be 'float32', 'int32' or 'bool'. Defaults to 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function zeros(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = zeros(shape, 'float32');
const imag = zeros(shape, 'float32');
return complex(real, imag);
}
const values = makeZerosTypedArray(sizeFromShape(shape), dtype);
return ENGINE.makeTensor(values, shape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1.
*
* ```js
* tf.ones([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function ones$1(shape, dtype = 'float32') {
if (dtype === 'complex64') {
const real = ones$1(shape, 'float32');
const imag = zeros(shape, 'float32');
return complex(real, imag);
}
const values = makeOnesTypedArray(sizeFromShape(shape), dtype);
return ENGINE.makeTensor(values, shape, dtype);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const meanGradConfig = {
kernelName: Mean,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { axis } = attrs;
const axes = parseAxisParam(axis, x.shape);
const shapes = computeOutAndReduceShapes(x.shape, axes);
const reduceShape = shapes[1];
const reduceSize = sizeFromShape(reduceShape);
const derX = () => {
const expandedDyShape = x.shape.slice();
axes.forEach(axis => {
expandedDyShape[axis] = 1;
});
const expandedDy = reshape(dy, expandedDyShape);
const res = div(mul(expandedDy, ones$1(x.shape, 'float32')), reduceSize);
return res;
};
return { x: derX };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const minGradConfig = {
kernelName: Min,
inputsToSave: ['x'],
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const minAttrs = attrs;
const { axis } = minAttrs;
const [x, y] = saved;
const origAxes = parseAxisParam(axis, x.shape);
const minGrad = gradForMinAndMax(dy, y, x, origAxes);
return {
x: () => {
return minGrad['x']();
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const minimumGradConfig = {
kernelName: Minimum,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const derA = () => mul(dy, cast(lessEqual(a, b), 'float32'));
const derB = () => mul(dy, cast(greater(a, b), 'float32'));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a slice from a `tf.Tensor` starting at coordinates `begin`
* and is of size `size`.
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `x` is of the given rank:
* - `tf.slice1d`
* - `tf.slice2d`
* - `tf.slice3d`
* - `tf.slice4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.slice([1], [2]).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* x.slice([1, 0], [1, 2]).print();
* ```
* @param x The input `tf.Tensor` to slice from.
* @param begin The coordinates to start the slice from. The length can be
* less than the rank of x - the rest of the axes will have implicit 0 as
* start. Can also be a single number, in which case it specifies the
* first axis.
* @param size The size of the slice. The length can be less than the rank of
* x - the rest of the axes will have implicit -1. A value of -1 requests
* the rest of the dimensions in the axis. Can also be a single number,
* in which case it specifies the size of the first axis.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function slice_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');
if ($x.rank === 0) {
throw new Error('Slicing scalar is not possible');
}
const inputs = { x: $x };
const attrs = { begin, size };
return ENGINE.runKernel(Slice, inputs, attrs);
}
const slice = op({ slice_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const mirrorPadGradConfig = {
kernelName: MirrorPad,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
// Pad introduces values around the original tensor, so the gradient
// slices the original shape out of the gradient.
const x = saved[0];
const { paddings } = attrs;
const begin = paddings.map(p => p[0]);
return { x: () => slice(dy, begin, x.shape) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes floor of input `tf.Tensor` element-wise: `floor(x)`.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.floor().print(); // or tf.floor(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function floor_(x) {
const $x = convertToTensor(x, 'x', 'floor');
const inputs = { x: $x };
return ENGINE.runKernel(Floor, inputs);
}
const floor = op({ floor_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const modGradConfig = {
kernelName: Mod,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(dy, reduceAxes), a.shape);
}
return dy;
};
const derB = () => {
const res = mul(dy, neg(floor(div(a, b))));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const multiplyGradConfig = {
kernelName: Multiply,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = mul(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
const res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), b.shape);
}
return res;
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const negGradConfig = {
kernelName: Neg,
gradFunc: (dy) => {
return { x: () => neg(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const oneHotGradConfig = {
kernelName: OneHot,
inputsToSave: ['indices'],
gradFunc: (dy, saved) => {
const indices = saved[0];
return { indices: () => zeros(indices.shape, 'float32') };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const onesLikeGradConfig = {
kernelName: OnesLike,
gradFunc: (dy) => {
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.
*
* ```js
* const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* tf.unstack(a).forEach(tensor => tensor.print());
* ```
*
* @param x A tensor object.
* @param axis The axis to unstack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function unstack_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');
assert(axis >= -$x.shape.length && axis < $x.shape.length, () => `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);
const inputs = { value: $x };
const attrs = { axis };
return ENGINE.runKernel(Unpack, inputs, attrs);
}
const unstack = op({ unstack_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const packGradConfig = {
kernelName: Pack,
saveAllInputs: true,
gradFunc: (dy, saved, attrs) => {
const { axis } = attrs;
const derTensors = unstack(dy, axis);
return derTensors.map(t => () => t);
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const padV2GradConfig = {
kernelName: PadV2,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
// Pad introduces values around the original tensor, so the gradient
// slices the original shape out of the gradient.
const x = saved[0];
const { paddings } = attrs;
const begin = paddings.map(p => p[0]);
return { x: () => slice(dy, begin, x.shape) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E]);
*
* x.log().print(); // or tf.log(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log_(x) {
const $x = convertToTensor(x, 'x', 'log');
const inputs = { x: $x };
return ENGINE.runKernel(Log, inputs);
}
const log$1 = op({ log_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the power of one `tf.Tensor` to another. Supports broadcasting.
*
* Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for
* corresponding elements in x and y. The result's dtype will be the upcasted
* type of the `base` and `exp` dtypes.
*
* ```js
* const a = tf.tensor([[2, 3], [4, 5]])
* const b = tf.tensor([[1, 2], [3, 0]]).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
*
* ```js
* const a = tf.tensor([[1, 2], [3, 4]])
* const b = tf.tensor(2).toInt();
*
* a.pow(b).print(); // or tf.pow(a, b)
* ```
* We also expose `powStrict` which has the same signature as this op and
* asserts that `base` and `exp` are the same shape (does not broadcast).
*
* @param base The base `tf.Tensor` to pow element-wise.
* @param exp The exponent `tf.Tensor` to pow element-wise.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function pow_(base, exp) {
let $base = convertToTensor(base, 'base', 'pow');
let $exp = convertToTensor(exp, 'exp', 'pow');
[$base, $exp] = makeTypesMatch($base, $exp);
const inputs = { a: $base, b: $exp };
return ENGINE.runKernel(Pow, inputs);
}
const pow = op({ pow_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const powGradConfig = {
kernelName: Pow,
inputsToSave: ['a', 'b'],
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [a, b, y] = saved;
const base = a;
const exp = b;
const outShape = assertAndGetBroadcastShape(base.shape, exp.shape);
const derBase = () => {
const expFloat = cast(exp, 'float32');
let res = mul(dy, mul(expFloat, pow(base, sub(expFloat, scalar(1)))));
const reduceAxes = getReductionAxes(base.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, base.shape);
};
const derExp = () => {
const condition = greater(base, 0);
const logBase = where(condition, log$1(base), zerosLike(base));
let res = mul(dy, mul(y, logBase));
const reduceAxes = getReductionAxes(exp.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, exp.shape);
};
return { a: derBase, b: derExp };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const preluGradConfig = {
kernelName: Prelu,
inputsToSave: ['x', 'alpha'],
gradFunc: (dy, saved) => {
const [x, alpha] = saved;
const mask = greater(x, 0);
return {
x: () => where(mask, dy, mul(dy, alpha)),
alpha: () => {
let res = where(mask, zerosLike(dy), mul(dy, x));
const reduceAxes = getReductionAxes(alpha.shape, dy.shape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, alpha.shape);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const divGradConfig = {
kernelName: RealDiv,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
const res = div(dy, cast(b, 'float32'));
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
return reshape(sum$1(res, reduceAxes), a.shape);
}
return res;
};
const derB = () => {
let res = mul(dy, cast(a, 'float32'));
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = reshape(sum$1(res, reduceAxes), b.shape);
}
const tmp = square(b);
return neg(div(res, cast(tmp, 'float32')));
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const reciprocalGradConfig = {
kernelName: Reciprocal,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, neg(square(x))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const relu6GradConfig = {
kernelName: Relu6,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
const mask = mul(lessEqual(x, 6), step(x));
return { x: () => mul(dy, cast(mask, 'float32')) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const reluGradConfig = {
kernelName: Relu,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, cast(step(x), 'float32')) };
}
};
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const reshapeGradConfig = {
kernelName: Reshape,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => reshape(dy, x.shape) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const resizeBilinearGradConfig = {
kernelName: ResizeBilinear,
inputsToSave: ['images'],
gradFunc: (dy, saved, attrs) => {
const [images] = saved;
const inputs = { dy, images };
const imagesDer = () =>
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(ResizeBilinearGrad, inputs, attrs);
return { images: imagesDer };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const resizeNearestNeighborGradConfig = {
kernelName: ResizeNearestNeighbor,
inputsToSave: ['images'],
gradFunc: (dy, saved, attrs) => {
const [images] = saved;
const inputs = { dy, images };
const imagesDer = () =>
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(ResizeNearestNeighborGrad, inputs, attrs);
return { images: imagesDer };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor` along a specified axis.
*
* Also available are stricter rank-specific methods that assert that `x` is
* of the given rank:
* - `tf.reverse1d`
* - `tf.reverse2d`
* - `tf.reverse3d`
* - `tf.reverse4d`
*
* Except `tf.reverse1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.reverse().print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.reverse(axis).print();
* ```
* @param x The input tensor to be reversed.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function reverse_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
const inputs = { x: $x };
const attrs = { dims: axis };
return ENGINE.runKernel(Reverse, inputs, attrs);
}
const reverse = op({ reverse_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const reverseGradConfig = {
kernelName: Reverse,
gradFunc: (dy, saved, attrs) => {
const { dims } = attrs;
const axes = parseAxisParam(dims, dy.shape);
return { x: () => reverse(dy, axes) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const roundGradConfig = {
kernelName: Round,
gradFunc: (dy) => {
// TODO(nsthorat): Let gradients be null for cases where we want to stop
// backpropgation.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const rsqrtGradConfig = {
kernelName: Rsqrt,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => neg(div(dy, mul(pow(x, 1.5), 2))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of `NOT x` element-wise.
*
* ```js
* const a = tf.tensor1d([false, true], 'bool');
*
* a.logicalNot().print();
* ```
*
* @param x The input tensor. Must be of dtype 'bool'.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalNot_(x) {
const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');
const inputs = { x: $x };
return ENGINE.runKernel(LogicalNot, inputs);
}
const logicalNot = op({ logicalNot_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const selectGradConfig = {
kernelName: Select,
inputsToSave: ['condition'],
gradFunc: (dy, saved) => {
const [condition] = saved;
return {
// TODO(julianoks): Return null for condition gradient
// when backprop supports it.
condition: () => cast(zerosLike(condition), 'float32'),
t: () => mul(dy, cast(condition, dy.dtype)),
e: () => mul(dy, cast(logicalNot(condition), dy.dtype))
};
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
const SELU_SCALEALPHA = 1.7580993408473768599402175208123;
const SELU_SCALE = 1.0507009873554804934193349852946;
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const seluGradConfig = {
kernelName: Selu,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return {
x: () => {
const mask = greater(x, scalar(0));
const scaleAlpha = scalar(SELU_SCALEALPHA);
const scale = scalar(SELU_SCALE);
const greaterThanZeroDer = mul(dy, scale);
const lessEqualZeroDer = mul(mul(dy, scaleAlpha), exp(cast(x, 'float32')));
return where(mask, greaterThanZeroDer, lessEqualZeroDer);
}
};
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const sigmoidGradConfig = {
kernelName: Sigmoid,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(dy, mul(y, sub(scalar(1), y))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const signGradConfig = {
kernelName: Sign,
gradFunc: (dy) => {
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes cos of the input `tf.Tensor` element-wise: `cos(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.cos().print(); // or tf.cos(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cos_(x) {
const $x = convertToTensor(x, 'x', 'cos');
const inputs = { x: $x };
return ENGINE.runKernel(Cos, inputs);
}
const cos = op({ cos_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const sinGradConfig = {
kernelName: Sin,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(cos(cast(x, 'float32')), dy) };
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.cosh().print(); // or tf.cosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function cosh_(x) {
const $x = convertToTensor(x, 'x', 'cosh');
const inputs = { x: $x };
return ENGINE.runKernel(Cosh, inputs);
}
const cosh = op({ cosh_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const sinhGradConfig = {
kernelName: Sinh,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(cosh(cast(x, 'float32')), dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` with a given value and paddings.
*
* This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,
* refer to `tf.mirrorPad`
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that `paddings` is of given length.
* - `tf.pad1d`
* - `tf.pad2d`
* - `tf.pad3d`
* - `tf.pad4d`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* x.pad([[1, 2]]).print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* @param constantValue The pad value to use. Defaults to 0.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function pad_(x, paddings, constantValue = 0) {
const $x = convertToTensor(x, 'x', 'pad');
if ($x.rank === 0) {
throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');
}
const attrs = { paddings, constantValue };
const inputs = { x: $x };
return ENGINE.runKernel(PadV2, inputs, attrs);
}
const pad = op({ pad_ });
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
function assertParamsValid(input, begin, size) {
const inputRank = input.shape.length;
assert(inputRank === begin.length, () => `Error in slice${inputRank}D: Length of begin ${begin} must ` +
`match the rank of the array (${inputRank}).`);
assert(inputRank === size.length, () => `Error in slice${inputRank}D: Length of size ${size} must ` +
`match the rank of the array (${inputRank}).`);
for (let i = 0; i < inputRank; ++i) {
assert(begin[i] + size[i] <= input.shape[i], () => `Error in slice${inputRank}D: begin[${i}] + size[${i}] ` +
`(${begin[i] + size[i]}) would overflow input.shape[${i}] (${input.shape[i]})`);
}
}
/** Converts a binary mask to an array of axes. Used in stridedSlice(). */
function maskToAxes(mask) {
const axes = [];
let axis = 0;
while (mask > 0) {
if (mask & 1) {
axes.push(axis);
}
mask /= 2;
axis++;
}
return axes;
}
/** Computes the output shape given the strided slice params. */
function computeOutShape(begin, end, strides) {
const size = [];
for (let axis = 0; axis < begin.length; axis++) {
size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);
}
return size;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stride value. Otherwise, insert.
function stridesWithElidedDims(strides, ellipsisInsertionIndex, numElidedAxes, inputShape) {
const newStrides = [...strides];
for (let i = newStrides.length; i < inputShape.length; i++) {
newStrides.push(1);
}
for (let i = 0; i < numElidedAxes; i++) {
if (i === 0) {
newStrides[ellipsisInsertionIndex] = 1;
}
else {
newStrides.splice(ellipsisInsertionIndex, 0 /* num elements to delete */, 1 /* element to add */);
newStrides.pop();
}
}
return newStrides;
}
function unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, normalizedAxis) {
if (normalizedAxis <= ellipsisInsertionIndex) {
return normalizedAxis;
}
return normalizedAxis - (numElidedAxes - 1);
}
function getElidedAxes(numElidedAxes, ellipsisInsertionIndex) {
const elidedAxes = [];
for (let i = 0; i < numElidedAxes; i++) {
elidedAxes.push(ellipsisInsertionIndex + i);
}
return elidedAxes;
}
// Normalize the start, end and strides.
function getNormalizedAxes(inputShape, ellipsisAxes, numInterpolatedAxes, begin, end, strides, beginMask, endMask, ellipsisMask) {
const inputRank = inputShape.length;
let normalizedBegin = new Array(inputRank), normalizedEnd = new Array(inputRank), normalizedStrides = new Array(inputRank);
if (ellipsisAxes.length && numInterpolatedAxes > 0) {
const fullIndex = ellipsisAxes[0];
// The ellipsis applies to the masked index as well as any dimensions
// that are interpolated.
const numElidedAxes = numInterpolatedAxes + 1;
normalizedBegin = startIndicesWithElidedDims(beginMask, fullIndex, numElidedAxes, begin, inputShape);
normalizedEnd = stopIndicesWithElidedDims(endMask, fullIndex, numElidedAxes, end, inputShape);
normalizedStrides =
stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);
}
else {
for (let axis = 0; axis < inputRank; axis++) {
normalizedBegin[axis] = startForAxis(beginMask, begin, strides, inputShape, axis, ellipsisMask);
normalizedEnd[axis] =
stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);
normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);
}
}
return {
begin: normalizedBegin,
end: normalizedEnd,
strides: normalizedStrides
};
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current start value. Otherwise, insert.
function startIndicesWithElidedDims(beginMask, ellipsisInsertionIndex, numElidedAxes, originalBegin, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = 0;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalBegin[originalAxis];
if (beginMask & 1 << originalAxis) {
originalValue = 0;
}
newIndices[axis] = originalValue;
}
}
return newIndices;
}
// Creates full selection at the elided dimensions. If the dimension matches
// the ellipsis mask, override the current stop value. Otherwise, insert.
function stopIndicesWithElidedDims(endMask, ellipsisInsertionIndex, numElidedAxes, originalEnd, inputShape) {
const newIndices = [...inputShape];
const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);
for (let axis = 0; axis < newIndices.length; axis++) {
if (elidedAxes.indexOf(axis) > -1) {
newIndices[axis] = Number.MAX_SAFE_INTEGER;
}
else {
const originalAxis = unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);
let originalValue = originalEnd[originalAxis];
if (endMask & 1 << originalAxis) {
originalValue = Number.MAX_SAFE_INTEGER;
}
newIndices[axis] = originalValue;
}
}
for (let i = 0; i < newIndices.length; i++) {
// Handle negative indices
const axisSize = inputShape[i];
if (newIndices[i] < 0) {
newIndices[i] += axisSize;
}
newIndices[i] = clamp(0, newIndices[i], inputShape[i]);
}
return newIndices;
}
function stridesForAxis(strides, axis, ellipsisMask) {
let stride = strides[axis];
if (ellipsisMask & (1 << axis) || stride == null) {
stride = 1;
}
return stride;
}
function startForAxis(beginMask, startIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let start = startIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or the begin index is not set
// for the axis.
if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {
if (stride > 0) {
// Forward iteration - use the first element. These values will get
// clamped below (Note: We could have set them to 0 and axis_size-1, but
// use lowest() and max() to maintain symmetry with StopForAxis())
start = Number.MIN_SAFE_INTEGER;
}
else {
// Backward iteration - use the last element.
start = Number.MAX_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (start < 0) {
start += axisSize;
}
// Clamping
start = clamp(0, start, axisSize - 1);
return start;
}
function stopForAxis(endMask, stopIndices, strides, inputShape, axis, ellipsisMask) {
// Begin with the specified index
let stop = stopIndices[axis];
const stride = strides[axis] || 1;
// Check the axis bit from right of masked axes, or if the stop index is not
// set for this axis.
if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {
if (stride > 0) {
// Forward iteration - use the last element. These values will get
// clamped below
stop = Number.MAX_SAFE_INTEGER;
}
else {
// Backward iteration - use the first element.
stop = Number.MIN_SAFE_INTEGER;
}
}
// Handle negative indices
const axisSize = inputShape[axis];
if (stop < 0) {
stop += axisSize;
}
// Clamping
// Because the end index points one past the last element, we need slightly
// different clamping ranges depending on the direction.
if (stride > 0) {
// Forward iteration
stop = clamp(0, stop, axisSize);
}
else {
// Backward iteration
stop = clamp(-1, stop, axisSize - 1);
}
return stop;
}
/**
* Returns true if the slice occupies a continous set of elements in the
* 'flat' space.
*/
function isSliceContinous(shape, begin, size) {
// Index of the first axis that has size > 1.
let firstNonOneAxis = size.length;
for (let i = 0; i < size.length; i++) {
if (size[i] > 1) {
firstNonOneAxis = i;
break;
}
}
for (let i = firstNonOneAxis + 1; i < size.length; i++) {
if (begin[i] > 0 || size[i] !== shape[i]) {
return false;
}
}
return true;
}
function computeFlatOffset(begin, strides) {
let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;
for (let i = 0; i < begin.length - 1; i++) {
flatOffset += begin[i] * strides[i];
}
return flatOffset;
}
function parseSliceParams(x, begin, size) {
// The following logic allows for more ergonomic calls.
let begin_;
const xRank = x.shape.length;
if (typeof begin === 'number') {
begin_ = [begin, ...new Array(xRank - 1).fill(0)];
}
else if (begin.length < xRank) {
begin_ = begin.concat(new Array(xRank - begin.length).fill(0));
}
else {
begin_ = begin.slice();
}
begin_.forEach(d => {
assert(d !== -1, () => 'slice() does not support negative begin indexing.');
});
let size_;
if (size == null) {
size_ = new Array(xRank).fill(-1);
}
else if (typeof size === 'number') {
size_ = [size, ...new Array(xRank - 1).fill(-1)];
}
else if (size.length < xRank) {
size_ = size.concat(new Array(xRank - size.length).fill(-1));
}
else {
size_ = size;
}
size_ = size_.map((d, i) => {
if (d >= 0) {
return d;
}
else {
assert(d === -1, () => `Negative size values should be exactly -1 but got ` +
`${d} for the slice() size at index ${i}.`);
return x.shape[i] - begin_[i];
}
});
return [begin_, size_];
}
function sliceInfo(xShape, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
// make a copy because it may be modified further down.
let $begin = begin.slice();
let $end = end.slice();
let $strides = strides;
if (strides == null) {
$strides = new Array($begin.length);
}
const ellipsisAxes = maskToAxes(ellipsisMask);
if (ellipsisAxes.length > 1) {
throw new Error('Multiple ellipses in slice is not allowed.');
}
if (ellipsisMask !== 0 && newAxisMask !== 0) {
throw new Error('Using both ellipsisMask and newAxisMask is not yet supported.');
}
if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {
throw new Error('Using both ellipsisMask and shrinkAxisMask is not yet supported.');
}
const numInterpolatedAxes = xShape.length - $begin.length;
// Expand the dims of x based on the newAxisMask.
const expandAxes = maskToAxes(newAxisMask);
const newShape = xShape.slice();
expandAxes.forEach(axis => {
$begin[axis] = 0;
$end[axis] = 1;
newShape.splice(axis, 0, 1);
});
const { begin: normalizedBegin, end: normalizedEnd, strides: normalizedStrides } = getNormalizedAxes(newShape, ellipsisAxes, numInterpolatedAxes, $begin, $end, $strides, beginMask, endMask, ellipsisMask);
$begin = normalizedBegin;
$end = normalizedEnd;
$strides = normalizedStrides;
const shrinkAxes = maskToAxes(shrinkAxisMask);
// Adjust the ends based on the shrink mask.
shrinkAxes.forEach(axis => {
$end[axis] = $begin[axis] + 1;
$strides[axis] = 1;
});
// Figure out the output shape.
const size = computeOutShape($begin, $end, $strides);
// Remove the axes based on shrinkMask.
const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);
const nonStrided = $strides.every(v => v === 1);
return { nonStrided, $begin, $end, $strides, size, newShape, outShape };
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const sliceGradConfig = {
kernelName: Slice,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { begin, size } = attrs;
const inputShape = x.shape;
const [begin_, size_] = parseSliceParams(x, begin, size);
// Create an Nx2 padding where the first column represents how many
// zeros are prepended (at start) for each dimension, and the second
// column indicates how many zeros are appended (at end).
// The number of zeros to append is the shape of the input
// elementwise-subtracted by both the begin vector and sizes vector.
const paddings = [];
for (let i = 0; i < dy.rank; i++) {
paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);
}
return { x: () => pad(dy, paddings) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const softmaxGradConfig = {
kernelName: Softmax,
outputsToSave: [true],
gradFunc: (dy, saved, attrs) => {
const [y] = saved;
const { dim } = attrs;
const keepDims = true;
const dyTimesY = mul(dy, y);
return {
logits: () => sub(dyTimesY, mul(sum$1(dyTimesY, [dim], keepDims), y))
};
}
};
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes sigmoid element-wise, `1 / (1 + exp(-x))`
*
* ```js
* const x = tf.tensor1d([0, -1, 2, -3]);
*
* x.sigmoid().print(); // or tf.sigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sigmoid_(x) {
const $x = convertToTensor(x, 'x', 'sigmoid');
const inputs = { x: $x };
return ENGINE.runKernel(Sigmoid, inputs);
}
const sigmoid = op({ sigmoid_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const softplusGradConfig = {
kernelName: Softplus,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, sigmoid(x)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of
* shape `blockShape + [batch]`, interleaves these blocks back into the grid
* defined by the spatial dimensions `[1, ..., M]`, to obtain a result with
* the same rank as the input. The spatial dimensions of this intermediate
* result are then optionally cropped according to `crops` to produce the
* output. This is the reverse of `tf.spaceToBatchND`. See below for a precise
* description.
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);
* const blockShape = [2, 2];
* const crops = [[0, 0], [0, 0]];
*
* x.batchToSpaceND(blockShape, crops).print();
* ```
*
* @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +
* remainingShape`, where spatialShape has `M` dimensions.
* @param blockShape A 1-D array. Must have shape `[M]`, all values must
* be >= 1.
* @param crops A 2-D array. Must have shape `[M, 2]`, all values must be >= 0.
* `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input
* dimension `i + 1`, which corresponds to spatial dimension `i`. It is required
* that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`
*
* This operation is equivalent to the following steps:
*
* 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,
* blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,
* x.shape[N-1]]`
*
* 2. Permute dimensions of `reshaped`to produce `permuted` of shape `[batch /
* prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /
* prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *
* blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`
*
* 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`
* according to `crops` to produce the output of shape: `[batch /
* prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],
* ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -
* crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function batchToSpaceND_(x, blockShape, crops) {
const $x = convertToTensor(x, 'x', 'batchToSpaceND');
const prod = blockShape.reduce((a, b) => a * b);
assert($x.rank >= 1 + blockShape.length, () => `input rank is ${$x.rank} but should be > than blockShape.length ${blockShape.length}`);
assert(crops.length === blockShape.length, () => `crops.length is ${crops.length} but should be equal to blockShape.length ${blockShape.length}`);
assert($x.shape[0] % prod === 0, () => `input tensor batch is ${$x.shape[0]} but is not divisible by the product of ` +
`the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);
const inputs = { x: $x };
const attrs = { blockShape, crops };
return ENGINE.runKernel(BatchToSpaceND, inputs, attrs);
}
const batchToSpaceND = op({ batchToSpaceND_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const spaceToBatchNDGradConfig = {
kernelName: SpaceToBatchND,
gradFunc: (dy, saved, attrs) => {
const { blockShape, paddings } = attrs;
return { x: () => batchToSpaceND(dy, blockShape, paddings) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Concatenates a list of `tf.Tensor`s along a given axis.
*
* The tensors ranks and types must match, and their sizes must match in all
* dimensions except `axis`.
*
* Also available are stricter rank-specific methods that assert that
* `tensors` are of the given rank:
* - `tf.concat1d`
* - `tf.concat2d`
* - `tf.concat3d`
* - `tf.concat4d`
*
* Except `tf.concat1d` (which does not have axis param), all methods have
* same signature as this method.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* a.concat(b).print(); // or a.concat(b)
* ```
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.concat([a, b, c]).print();
* ```
*
* ```js
* const a = tf.tensor2d([[1, 2], [10, 20]]);
* const b = tf.tensor2d([[3, 4], [30, 40]]);
* const axis = 1;
* tf.concat([a, b], axis).print();
* ```
* @param tensors A list of tensors to concatenate.
* @param axis The axis to concate along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function concat_(tensors, axis = 0) {
assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');
const $tensors = convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');
if ($tensors[0].dtype === 'complex64') {
$tensors.forEach(tensor => {
if (tensor.dtype !== 'complex64') {
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${tensor.dtype}. `);
}
});
}
if ($tensors.length === 1) {
return clone($tensors[0]);
}
const inputs = $tensors;
const attr = { axis };
return ENGINE.runKernel(Concat, inputs, attr);
}
const concat = op({ concat_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const splitVGradConfig = {
kernelName: SplitV,
gradFunc: (dy, saved, attrs) => {
const { axis } = attrs;
return { x: () => concat(dy, axis) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const sqrtGradConfig = {
kernelName: Sqrt,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, mul(sqrt(cast(x, 'float32')), 2)) };
}
};
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
const squareGradConfig = {
kernelName: Square,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => mul(dy, mul(cast(x, 'float32'), 2)) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const squaredDifferenceGradConfig = {
kernelName: SquaredDifference,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const two = scalar(2);
const derA = () => mul(dy, mul(two, sub(a, b)));
const derB = () => mul(dy, mul(two, sub(b, a)));
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const stepGradConfig = {
kernelName: Step,
gradFunc: (dy) => {
// TODO(manrajgrover): Return null for gradients when backprop supports
// it.
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const subGradConfig = {
kernelName: Sub,
inputsToSave: ['a', 'b'],
gradFunc: (dy, saved) => {
const [a, b] = saved;
const outShape = assertAndGetBroadcastShape(a.shape, b.shape);
const derA = () => {
let res = dy;
const reduceAxes = getReductionAxes(a.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, a.shape);
};
const derB = () => {
let res = dy;
const reduceAxes = getReductionAxes(b.shape, outShape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(neg(res), b.shape);
};
return { a: derA, b: derB };
}
};
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const sumGradConfig = {
kernelName: Sum,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const expandedDyShape = x.shape.slice();
const { axis } = attrs;
const axes = parseAxisParam(axis, x.shape);
axes.forEach(axis => {
expandedDyShape[axis] = 1;
});
const expandedDy = reshape(dy, expandedDyShape);
const derX = mul(expandedDy, ones$1(x.shape, 'float32'));
return { x: () => derX };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const tanGradConfig = {
kernelName: Tan,
inputsToSave: ['x'],
gradFunc: (dy, saved) => {
const [x] = saved;
return { x: () => div(dy, square(cos(x))) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const tanhGradConfig = {
kernelName: Tanh,
outputsToSave: [true],
gradFunc: (dy, saved) => {
const [y] = saved;
return { x: () => mul(sub(scalar(1), square(y)), dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const tileGradConfig = {
kernelName: Tile,
inputsToSave: ['x'],
gradFunc: (dy, saved, attrs) => {
const [x] = saved;
const { reps } = attrs;
const derX = () => {
let xGrad = zerosLike(x);
// TODO(cais): Maybe reduce memory footprint by avoiding repeated
// slicing.
if (x.rank === 1) {
for (let i = 0; i < reps[0]; ++i) {
xGrad = add$1(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));
}
}
else if (x.rank === 2) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
xGrad = add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1]], [
x.shape[0], x.shape[1]
]));
}
}
}
else if (x.rank === 3) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
xGrad =
add$1(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1], k * x.shape[2]], [x.shape[0], x.shape[1], x.shape[2]]));
}
}
}
}
else if (x.rank === 4) {
for (let i = 0; i < reps[0]; ++i) {
for (let j = 0; j < reps[1]; ++j) {
for (let k = 0; k < reps[2]; ++k) {
for (let l = 0; l < reps[3]; ++l) {
xGrad =
add$1(xGrad, slice(dy, [
i * x.shape[0], j * x.shape[1], k * x.shape[2],
l * x.shape[3]
], [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));
}
}
}
}
}
else {
throw new Error(`Gradient for tile operation is not implemented for rank-` +
`${x.rank} tensors yet.`);
}
return xGrad;
};
return { x: derX };
},
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const transposeGradConfig = {
kernelName: Transpose,
gradFunc: (dy, saved, attrs) => {
const transposeAttrs = attrs;
const { perm } = transposeAttrs;
const undoPerm = getUndoAxesPermutation(perm);
return { x: () => transpose(dy, undoPerm) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
* tf.stack([a, b, c]).print();
* ```
*
* @param tensors A list of tensor objects with the same shape and dtype.
* @param axis The axis to stack along. Defaults to 0 (the first dim).
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function stack_(tensors, axis = 0) {
const $tensors = convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');
assert($tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');
if ($tensors.length > 0) {
assert(axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');
}
const inputs = $tensors;
const attrs = { axis };
return ENGINE.runKernel(Pack, inputs, attrs);
}
const stack = op({ stack_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const unpackGradConfig = {
kernelName: Unpack,
gradFunc: (dy, saved, attrs) => {
const unpackAttrs = attrs;
const { axis } = unpackAttrs;
return { value: () => stack(dy, axis) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns a `tf.Tensor` that has expanded rank, by inserting a dimension
* into the tensor's shape.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const axis = 1;
* x.expandDims(axis).print();
* ```
*
* @param x The input tensor whose dimensions to be expanded.
* @param axis The dimension index at which to insert shape of `1`. Defaults
* to 0 (the first dimension).
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function expandDims_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');
assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');
const inputs = { input: $x };
const attrs = { dim: axis };
return ENGINE.runKernel(ExpandDims, inputs, attrs);
}
const expandDims = op({ expandDims_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Gather slices from tensor `x`'s axis `axis` according to `indices`.
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
* const indices = tf.tensor1d([1, 3, 3], 'int32');
*
* x.gather(indices).print();
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const indices = tf.tensor1d([1, 1, 0], 'int32');
*
* x.gather(indices).print();
* ```
* @param x The input tensor whose slices to be gathered.
* @param indices The indices of the values to extract.
* @param axis The axis over which to select values. Defaults to 0.
* @param batchDims Optional. The number of batch dimensions. It must be less
* than or equal to rank(indices). Defaults to 0.
* The output tensor will have shape of
* `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
function gather_(x, indices, axis = 0, batchDims = 0) {
const $x = convertToTensor(x, 'x', 'gather');
const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');
const inputs = { x: $x, indices: $indices };
const attrs = { axis, batchDims };
return ENGINE.runKernel(GatherV2, inputs, attrs);
}
const gather = op({ gather_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the max of a and b (`a > b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `tf.maximumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* ```js
* // Broadcast maximum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.maximum(b).print(); // or tf.maximum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function maximum_(a, b) {
let $a = convertToTensor(a, 'a', 'maximum');
let $b = convertToTensor(b, 'b', 'maximum');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'bool') {
$a = cast($a, 'int32');
$b = cast($b, 'int32');
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Maximum, inputs);
}
const maximum = op({ maximum_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const unsortedSegmentSumGradConfig = {
kernelName: UnsortedSegmentSum,
inputsToSave: ['segmentIds'],
gradFunc: (dy, saved) => {
const [segmentIds] = saved;
const derX = () => {
return gatherDropNegatives(dy, segmentIds);
};
return { x: derX };
}
};
function gatherDropNegatives(x, indices) {
// Helper function for unsorted segment ops. Gathers params for
// positive segment ids and gathers 0 for inputs with negative segment id.
// Mirrors _GatherDropNegatives from tensorflow/python/ops/math_grad.py
const zeroClippedIndices = maximum(indices, zerosLike(indices));
const gathered = gather(x, zeroClippedIndices);
let isPositive = greaterEqual(indices, scalar(0, 'int32'));
const numIters = gathered.rank - isPositive.rank;
for (let i = 0; i < numIters; ++i) {
isPositive = expandDims(isPositive, i + 1);
}
isPositive = logicalAnd(isPositive, ones$1(gathered.shape, 'bool'));
const zeroSlice = zerosLike(gathered);
return where(isPositive, gathered, zeroSlice);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const zerosLikeGradConfig = {
kernelName: ZerosLike,
gradFunc: (dy) => {
return { x: () => zerosLike(dy) };
}
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
// Export all kernel configs here so that the package can auto register them
const gradConfigs = [
absGradConfig,
acosGradConfig,
acoshGradConfig,
addGradConfig,
addNGradConfig,
argMaxGradConfig,
argMinGradConfig,
asinGradConfig,
asinhGradConfig,
atan2GradConfig,
atanGradConfig,
atanhGradConfig,
avgPool3DGradConfig,
avgPoolGradConfig,
batchMatMulGradConfig,
batchToSpaceNDGradConfig,
broadcastToGradConfig,
castGradConfig,
ceilGradConfig,
clipByValueGradConfig,
complexAbsGradConfig,
concatGradConfig,
conv2DBackpropInputGradConfig,
conv2DGradConfig,
conv3DGradConfig,
cosGradConfig,
coshGradConfig,
cumsumGradConfig,
depthwiseConv2dNativeGradConfig,
dilation2dGradConfig,
divGradConfig,
eluGradConfig,
erfGradConfig,
expGradConfig,
expandDimsGradConfig,
expm1GradConfig,
floorDivGradConfig,
floorGradConfig,
fusedBatchNormGradConfig,
gatherGradConfig,
greaterEqualGradConfig,
identityGradConfig,
isFiniteGradConfig,
isInfGradConfig,
isNanGradConfig,
leakyReluGradConfig,
log1pGradConfig,
logGradConfig,
logSoftmaxGradConfig,
lrnGradConfig,
maxGradConfig,
maxGradConfig,
maximumGradConfig,
maxPool3DGradConfig,
maxPoolGradConfig,
meanGradConfig,
minGradConfig,
minimumGradConfig,
mirrorPadGradConfig,
modGradConfig,
multiplyGradConfig,
negGradConfig,
oneHotGradConfig,
onesLikeGradConfig,
packGradConfig,
padV2GradConfig,
padV2GradConfig,
powGradConfig,
preluGradConfig,
reciprocalGradConfig,
relu6GradConfig,
reluGradConfig,
reshapeGradConfig,
resizeBilinearGradConfig,
resizeNearestNeighborGradConfig,
reverseGradConfig,
roundGradConfig,
rsqrtGradConfig,
selectGradConfig,
seluGradConfig,
sigmoidGradConfig,
signGradConfig,
sinGradConfig,
sinhGradConfig,
sliceGradConfig,
softmaxGradConfig,
softplusGradConfig,
spaceToBatchNDGradConfig,
spaceToBatchNDGradConfig,
splitVGradConfig,
splitVGradConfig,
sqrtGradConfig,
squaredDifferenceGradConfig,
squareGradConfig,
stepGradConfig,
subGradConfig,
sumGradConfig,
tanGradConfig,
tanhGradConfig,
tileGradConfig,
transposeGradConfig,
unpackGradConfig,
unsortedSegmentSumGradConfig,
zerosLikeGradConfig
];
for (const gradientConfig of gradConfigs) {
registerGradient(gradientConfig);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes absolute value element-wise: `abs(x)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.abs().print(); // or tf.abs(x)
* ```
* @param x The input `tf.Tensor`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function abs_(x) {
const $x = convertToTensor(x, 'x', 'abs');
if ($x.dtype === 'complex64') {
const inputs = { x: $x };
return ENGINE.runKernel(ComplexAbs, inputs);
}
else {
const inputs = { x: $x };
return ENGINE.runKernel(Abs, inputs);
}
}
const abs = op({ abs_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes acos of the input `tf.Tensor` element-wise: `acos(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.acos().print(); // or tf.acos(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acos_(x) {
const $x = convertToTensor(x, 'x', 'acos');
const inputs = { x: $x };
return ENGINE.runKernel(Acos, inputs);
}
const acos = op({ acos_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:
* `acosh(x)`
*
* ```js
* const x = tf.tensor1d([10, 1, 3, 5.7]);
*
* x.acosh().print(); // or tf.acosh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function acosh_(x) {
const $x = convertToTensor(x, 'x', 'acosh');
const inputs = { x: $x };
return ENGINE.runKernel(Acosh, inputs);
}
const acosh = op({ acosh_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor1d([3, 4]);
* const c = tf.tensor1d([5, 6]);
*
* tf.addN([a, b, c]).print();
* ```
* @param tensors A list of tensors with the same shape and dtype.
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function addN_(tensors) {
assert(Array.isArray(tensors), () => 'The argument passed to tf.addN() must be a list of tensors');
assert(tensors.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ` +
`${tensors.length}`);
const $tensors = tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));
const firstTensor = $tensors[0];
$tensors.forEach(t => {
if (t.dtype !== firstTensor.dtype) {
throw new Error('All tensors passed to tf.addN() must have the same dtype');
}
});
$tensors.forEach(t => {
if (!arraysEqual(t.shape, firstTensor.shape)) {
throw new Error('All tensors passed to tf.addN() must have the same shape');
}
});
const inputs = $tensors;
return ENGINE.runKernel(AddN, inputs);
}
const addN = op({ addN_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the logical and of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.all().print(); // or tf.all(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.all(axis).print(); // or tf.all(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function all_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'all', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(All, inputs, attrs);
}
const all = op({ all_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the logical or of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 1, 1], 'bool');
*
* x.any().print(); // or tf.any(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');
*
* const axis = 1;
* x.any(axis).print(); // or tf.any(x, axis)
* ```
*
* @param x The input tensor. Must be of dtype bool.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function any_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'any', 'bool');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Any, inputs, attrs);
}
// tslint:disable-next-line:variable-name
const any = op({ any_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Returns the indices of the maximum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMax().print(); // or tf.argMax(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMax(axis).print(); // or tf.argMax(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMax_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'argMax');
const inputs = { x: $x };
const attrs = { axis };
return ENGINE.runKernel(ArgMax, inputs, attrs);
}
const argMax = op({ argMax_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Returns the indices of the minimum values along an `axis`.
*
* The result has the same shape as `input` with the dimension along `axis`
* removed.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.argMin().print(); // or tf.argMin(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);
*
* const axis = 1;
* x.argMin(axis).print(); // or tf.argMin(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function argMin_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'argMin');
const inputs = { x: $x };
const attrs = { axis };
return ENGINE.runKernel(ArgMin, inputs, attrs);
}
const argMin = op({ argMin_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes asin of the input `tf.Tensor` element-wise: `asin(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asin().print(); // or tf.asin(x)
* ```
* @param x The input tensor.
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asin_(x) {
const $x = convertToTensor(x, 'x', 'asin');
const inputs = { x: $x };
return ENGINE.runKernel(Asin, inputs);
}
const asin = op({ asin_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:
* `asinh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.asinh().print(); // or tf.asinh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function asinh_(x) {
const $x = convertToTensor(x, 'x', 'asinh');
const inputs = { x: $x };
return ENGINE.runKernel(Asinh, inputs);
}
const asinh = op({ asinh_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes atan of the input `tf.Tensor` element-wise: `atan(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.atan().print(); // or tf.atan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan_(x) {
const $x = convertToTensor(x, 'x', 'atan');
const inputs = { x: $x };
return ENGINE.runKernel(Atan, inputs);
}
const atan = op({ atan_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);
* const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);
*
* tf.atan2(a, b).print()
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atan2_(a, b) {
let $a = convertToTensor(a, 'a', 'atan2');
let $b = convertToTensor(b, 'b', 'atan2');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Atan2, inputs);
}
const atan2 = op({ atan2_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:
* `atanh(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.atanh().print(); // or tf.atanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function atanh_(x) {
const $x = convertToTensor(x, 'x', 'atanh');
const inputs = { x: $x };
return ENGINE.runKernel(Atanh, inputs);
}
const atanh = op({ atanh_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the 2D average pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function avgPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'avgPool', 'float32');
const dilations = 1;
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in avgPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(AvgPool, inputs, attrs);
res = cast(res, $x.dtype);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const avgPool = op({ avgPool_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the 3D average pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.avgPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function avgPool3d_(x, filterSize, strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
assert(dataFormat === 'NDHWC', () => `Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in avgPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(AvgPool3D, inputs, attrs);
res = cast(res, x5D.dtype);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const avgPool3d = op({ avgPool3d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, 70]);
*
* x.tanh().print(); // or tf.tanh(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tanh_(x) {
const $x = convertToTensor(x, 'x', 'tanh');
const inputs = { x: $x };
return ENGINE.runKernel(Tanh, inputs);
}
const tanh$1 = op({ tanh_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the next state and output of a BasicLSTMCell.
*
* Returns `[newC, newH]`.
*
* Derived from tf.contrib.rnn.BasicLSTMCell.
*
* @param forgetBias Forget bias for the cell.
* @param lstmKernel The weights for the cell.
* @param lstmBias The bias for the cell.
* @param data The input to the cell.
* @param c Previous cell state.
* @param h Previous cell output.
*
* @doc {heading: 'Operations', subheading: 'RNN'}
*/
function basicLSTMCell_(forgetBias, lstmKernel, lstmBias, data, c, h) {
const $forgetBias = convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');
const $lstmKernel = convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');
const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');
const $data = convertToTensor(data, 'data', 'basicLSTMCell');
const $c = convertToTensor(c, 'c', 'basicLSTMCell');
const $h = convertToTensor(h, 'h', 'basicLSTMCell');
const combined = concat([$data, $h], 1);
const weighted = matMul(combined, $lstmKernel);
const res = add$1(weighted, $lstmBias);
// i = input_gate, j = new_input, f = forget_gate, o = output_gate
const batchSize = res.shape[0];
const sliceCols = res.shape[1] / 4;
const sliceSize = [batchSize, sliceCols];
const i = slice(res, [0, 0], sliceSize);
const j = slice(res, [0, sliceCols], sliceSize);
const f = slice(res, [0, sliceCols * 2], sliceSize);
const o = slice(res, [0, sliceCols * 3], sliceSize);
const newC = add$1(mul(sigmoid(i), tanh$1(j)), mul($c, sigmoid(add$1($forgetBias, f))));
const newH = mul(tanh$1(newC), sigmoid(o));
return [newC, newH];
}
const basicLSTMCell = op({ basicLSTMCell_ });
function xAs4D(x) {
let x4D;
if (x.rank === 0 || x.rank === 1) {
x4D = reshape(x, [1, 1, 1, x.size]);
}
else if (x.rank === 2) {
x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);
}
else if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
else {
x4D = x;
}
return x4D;
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Batch normalization.
*
* As described in
* [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).
*
* Mean, variance, scale, and offset can be of two shapes:
* - The same shape as the input.
* - In the common case, the depth dimension is the last dimension of x, so
* the values would be an `tf.Tensor1D` of shape [depth].
*
* Also available are stricter rank-specific methods with the same signature
* as this method that assert that parameters passed are of given rank
* - `tf.batchNorm2d`
* - `tf.batchNorm3d`
* - `tf.batchNorm4d`
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function batchNorm_(x, mean, variance, offset, scale, varianceEpsilon) {
if (varianceEpsilon == null) {
varianceEpsilon = 0.001;
}
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($mean.rank === $variance.rank, () => 'Batch normalization gradient requires mean and variance to have ' +
'equal ranks.');
assert($offset == null || $mean.rank === $offset.rank, () => 'Batch normalization gradient requires mean and offset to have ' +
'equal ranks.');
assert($scale == null || $mean.rank === $scale.rank, () => 'Batch normalization gradient requires mean and scale to have ' +
'equal ranks.');
const x4D = xAs4D($x);
const inputs = {
x: x4D,
scale: $scale,
offset: $offset,
mean: $mean,
variance: $variance
};
const attrs = { varianceEpsilon };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(FusedBatchNorm, inputs, attrs);
return reshape(res, $x.shape);
}
const batchNorm = op({ batchNorm_ });
/**
* Batch normalization, strictly for 2D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm2d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 2, () => `Error in batchNorm2D: x must be rank 2 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 2 || $mean.rank === 1, () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 2 || $variance.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 2 || $scale.rank === 1, () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 2 || $offset.rank === 1, () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm2d = op({ batchNorm2d_ });
/**
* Batch normalization, strictly for 3D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm3d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 3, () => `Error in batchNorm3D: x must be rank 3 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 3 || $mean.rank === 1, () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 3 || $variance.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 3 || $scale.rank === 1, () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 3 || $offset.rank === 1, () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm3d = op({ batchNorm3d_ });
/**
* Batch normalization, strictly for 4D. For the more relaxed version, see
* `tf.batchNorm`.
*
* @param x The input Tensor.
* @param mean A mean Tensor.
* @param variance A variance Tensor.
* @param offset An offset Tensor.
* @param scale A scale Tensor.
* @param varianceEpsilon A small float number to avoid dividing by 0.
*/
function batchNorm4d_(x, mean, variance, offset, scale, varianceEpsilon) {
const $x = convertToTensor(x, 'x', 'batchNorm');
const $mean = convertToTensor(mean, 'mean', 'batchNorm');
const $variance = convertToTensor(variance, 'variance', 'batchNorm');
let $scale;
if (scale != null) {
$scale = convertToTensor(scale, 'scale', 'batchNorm');
}
let $offset;
if (offset != null) {
$offset = convertToTensor(offset, 'offset', 'batchNorm');
}
assert($x.rank === 4, () => `Error in batchNorm4D: x must be rank 4 but got rank ` +
`${$x.rank}.`);
assert($mean.rank === 4 || $mean.rank === 1, () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +
`got rank ${$mean.rank}.`);
assert($variance.rank === 4 || $variance.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +
`but got rank ${$variance.rank}.`);
if ($scale != null) {
assert($scale.rank === 4 || $scale.rank === 1, () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +
`but got rank ${$scale.rank}.`);
}
if ($offset != null) {
assert($offset.rank === 4 || $offset.rank === 1, () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +
`but got rank ${$offset.rank}.`);
}
return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);
}
const batchNorm4d = op({ batchNorm4d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function bincount_(x, weights, size) {
const $x = convertToTensor(x, 'x', 'bincount');
const $weights = convertToTensor(weights, 'weights', 'bincount');
assert($x.dtype === 'int32', () => `Error in bincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
assert(size >= 0, () => `size must be non-negative, but got ${size}.`);
assert($weights.size === $x.size || $weights.size === 0, () => `Error in bincount: weights must have the same size as input or` +
`0-length, but got input shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size };
return ENGINE.runKernel(Bincount, inputs, attrs);
}
const bincount = op({ bincount_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Return the shape of s0 op s1 with broadcast.
*
* compute r0, the broadcasted shape as a tensor.
* s0, s1 and r0 are all integer vectors.
*
* This function returns the shape of the result of an operation between
* two tensors of size s0 and s1 performed with broadcast.
*
* @param s0 A tensor representing a shape
* @param s1 A tensor representing a shape
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function broadcastArgs_(s0, s1) {
const shape1Input = convertToTensor(s0, 's0', 'broadcastArgs', 'int32');
const shape2Input = convertToTensor(s1, 's1', 'broadcastArgs', 'int32');
if (shape1Input.rank !== 1) {
throw new Error('broadcastArgs(): first input must be a vector (rank=1). ' +
`Has rank ${shape1Input.rank}`);
}
if (shape2Input.rank !== 1) {
throw new Error('broadcastArgs(): second input must be a vector (rank=1). ' +
`Has rank ${shape2Input.rank}`);
}
const inputs = { s0: shape1Input, s1: shape2Input };
return ENGINE.runKernel(BroadcastArgs, inputs);
}
const broadcastArgs = op({ broadcastArgs_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.
*
* The values are stored in CPU as `TypedArray`. Fill the buffer using
* `buffer.set()`, or by modifying directly `buffer.values`.
*
* When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with
* those values.
*
* ```js
* // Create a buffer and set values at particular indices.
* const buffer = tf.buffer([2, 2]);
* buffer.set(3, 0, 0);
* buffer.set(5, 1, 0);
*
* // Convert the buffer back to a tensor.
* buffer.toTensor().print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param dtype The dtype of the buffer. Defaults to 'float32'.
* @param values The values of the buffer as `TypedArray`. Defaults to
* zeros.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function buffer(shape, dtype = 'float32', values) {
dtype = dtype || 'float32';
assertNonNegativeIntegerDimensions(shape);
return new TensorBuffer(shape, dtype, values);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.ceil().print(); // or tf.ceil(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function ceil_(x) {
const $x = convertToTensor(x, 'x', 'ceil');
const inputs = { x: $x };
return ENGINE.runKernel(Ceil, inputs);
}
const ceil = op({ ceil_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.clipByValue(-2, 3).print(); // or tf.clipByValue(x, -2, 3)
* ```
* @param x The input tensor.
* @param clipValueMin Lower-bound of range to be clipped to.
* @param clipValueMax Upper-bound of range to be clipped to.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function clipByValue_(x, clipValueMin, clipValueMax) {
const $x = convertToTensor(x, 'x', 'clipByValue');
assert((clipValueMin <= clipValueMax), () => `Error in clip: min (${clipValueMin}) must be ` +
`less than or equal to max (${clipValueMax}).`);
const inputs = { x: $x };
const attrs = { clipValueMin, clipValueMax };
return ENGINE.runKernel(ClipByValue, inputs, attrs);
}
const clipByValue = op({ clipByValue_ });
/**
* Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(3) = |r1, g1, b1|
* B: shape(2) = |r2, g2|
* C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @return The concatenated array.
*/
function concat1d_(tensors) {
return concat(tensors, 0 /* axis */);
}
const concat1d = op({ concat1d_ });
/**
* Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.
*
* For example, if:
* A: shape(2, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat2d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concatenate along.
* @return The concatenated array.
*/
function concat2d_(tensors, axis) {
return concat(tensors, axis);
}
const concat2d = op({ concat2d_ });
/**
* Concatenates a list of `tf.Tensor3D`s along an axis.
* See `concat` for details.
*
* For example, if:
* A: shape(2, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
*
* B: shape(2, 1, 3) = | r3, g3, b3 |
* | r4, g4, b4 |
*
* C = tf.concat3d([A, B], axis)
*
* if axis = 0:
* C: shape(4, 1, 3) = | r1, g1, b1 |
* | r2, g2, b2 |
* | r3, g3, b3 |
* | r4, g4, b4 |
*
* if axis = 1:
* C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* if axis = 2:
* C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |
* | r2, g2, b2, r4, g4, b4 |
*
* @param tensors A list of`tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat3d_(tensors, axis) {
return concat(tensors, axis);
}
const concat3d = op({ concat3d_ });
/**
* Concatenates a list of `tf.Tensor4D`s along an axis.
* See `concat` for details.
*
* @param tensors A list of `tf.Tensor`s to concatenate.
* @param axis The axis to concate along.
* @return The concatenated array.
*/
function concat4d_(tensors, axis) {
return concat(tensors, axis);
}
const concat4d = op({ concat4d_ });
/**
* Computes a 1D convolution over the input x.
*
* @param x The input tensor, of rank 3 or rank 2, of shape
* `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.
* @param filter The filter, rank 3, of shape
* `[filterWidth, inDepth, outDepth]`.
* @param stride The number of entries by which the filter is moved right at
* each step.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat An optional string from "NWC", "NCW". Defaults to "NWC",
* the data is stored in the order of [batch, in_width, in_channels]. Only
* "NWC" is currently supported.
* @param dilation The dilation rate in which we sample input values in
* atrous convolution. Defaults to `1`. If it is greater than 1, then
* stride must be `1`.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv1d_(x, filter, stride, pad, dataFormat = 'NWC', dilation = 1, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv1d');
const $filter = convertToTensor(filter, 'filter', 'conv1d');
let x3D = $x;
let reshapedTo3D = false;
if ($x.rank === 2) {
reshapedTo3D = true;
x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);
}
assert(x3D.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);
assert($filter.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in conv1d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
assert(x3D.shape[2] === $filter.shape[1], () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +
`input depth for filter ${$filter.shape[1]}.`);
assert(eitherStridesOrDilationsAreOne(stride, dilation), () => 'Error in conv1D: Either stride or dilation must be 1. ' +
`Got stride ${stride} and dilation '${dilation}'`);
assert(dataFormat === 'NWC', () => `Error in conv1d: got dataFormat of ${dataFormat} but only NWC is currently supported.`);
const filter4D = reshape($filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);
const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);
const strides = [1, stride];
const dilations = [1, dilation];
const conv2dDataFormat = 'NHWC';
const res = conv2d(input4D, filter4D, strides, pad, conv2dDataFormat, dilations, dimRoundingMode);
if (reshapedTo3D) {
return reshape(res, [res.shape[2], res.shape[3]]);
}
return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]);
}
const conv1d = op({ conv1d_ });
/**
* Computes the transposed 2D convolution of an image, also known as a
* deconvolution.
*
* @param x The input image, of rank 4 or rank 3, of shape
* `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 4 or rank 3:
* `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.
* @param strides The strides of the original convolution:
* `[strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv2dTranspose_(x, filter, outputShape, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'conv2dTranspose');
const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');
return conv2DBackpropInput(outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);
}
const conv2dTranspose = op({ conv2dTranspose_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes a 3D convolution over the input x.
*
* @param x The input tensor, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, channels]`. If rank 4,
* batch of 1 is assumed.
* @param filter The filter, rank 5, of shape
* `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.
* inChannels must match between input and filter.
* @param strides The strides of the convolution: `[strideDepth, strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat: An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param dilations The dilation rates: `[dilationDepth, dilationHeight,
* dilationWidth]` in which we sample input values across the height
* and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.
* If `dilations` is a single number, then
* `dilationDepth == dilationHeight == dilationWidth`. If it is greater
* than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv3d_(x, filter, strides, pad, dataFormat = 'NDHWC', dilations = [1, 1, 1]) {
const $x = convertToTensor(x, 'x', 'conv3d');
const $filter = convertToTensor(filter, 'filter', 'conv3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);
assert($filter.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ` +
`${$filter.rank}.`);
assert(x5D.shape[4] === $filter.shape[3], () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +
`input depth for filter ${$filter.shape[3]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv3D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
assert(dataFormat === 'NDHWC', () => `Error in conv3d: got dataFormat of ${dataFormat} but only NDHWC is currently supported.`);
const inputs = { x: x5D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Conv3D, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const conv3d = op({ conv3d_ });
/**
* Computes the transposed 3D convolution of a volume, also known as a
* deconvolution.
*
* @param x The input image, of rank 5 or rank 4, of shape
* `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.
* @param filter The filter, rank 4, of shape
* `[depth, filterHeight, filterWidth, outDepth, inDepth]`.
* `inDepth` must match `inDepth` in `x`.
* @param outputShape Output shape, of rank 5 or rank 4:
* `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is
* assumed.
* @param strides The strides of the original convolution:
* `[strideDepth, strideHeight, strideWidth]`.
* @param pad The type of padding algorithm used in the non-transpose version
* of the op.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function conv3dTranspose_(x, filter, outputShape, strides, pad) {
const $x = convertToTensor(x, 'x', 'conv3dTranspose');
const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');
return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);
}
const conv3dTranspose = op({ conv3dTranspose_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Outputs a vector with length `size` and the same dtype as `weights`.
*
* If `weights` are empty, then index `i` stores the number of times the value
* `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the
* sum of the value in `weights` at each index where the corresponding value in
* `x` is `i`.
*
* Values in `x` outside of the range [0, size) are ignored.
*
* @param x The input int tensor, rank 1 or rank 2.
* @param weights The weights tensor, must have the same shape as x, or a
* length-0 Tensor, in which case it acts as all weights equal to 1.
* @param size Non-negative integer.
* @param binaryOutput Optional. Whether the kernel should count the appearance
* or number of occurrences. Defaults to False.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function denseBincount_(x, weights, size, binaryOutput = false) {
const $x = convertToTensor(x, 'x', 'denseBincount');
const $weights = convertToTensor(weights, 'weights', 'denseBincount');
assert($x.dtype === 'int32', () => `Error in denseBincount: input ` +
`dtype must be int32, but got ${$x.dtype}`);
assert($x.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got ` +
`rank ${$x.rank}.`);
assert(size >= 0, () => `size must be non-negative, but got ${size}.`);
assert($weights.size === $x.size || $weights.size === 0, () => `Error in denseBincount: weights must have the same shape as x or ` +
`0-length, but got x shape: ${$x.shape}, weights shape: ` +
`${$weights.shape}.`);
const inputs = { x: $x, weights: $weights };
const attrs = { size, binaryOutput };
return ENGINE.runKernel(DenseBincount, inputs, attrs);
}
const denseBincount = op({ denseBincount_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Rearranges data from depth into blocks of spatial data. More specifically,
* this op outputs a copy of the input tensor where values from the `depth`
* dimension are moved in spatial blocks to the `height` and `width` dimensions.
* The attr `blockSize` indicates the input block size and how the data is
* moved.
*
* - Chunks of data of size `blockSize * blockSize` from depth are rearranged
* into non-overlapping blocks of size `blockSize x blockSize`
*
* - The width the output tensor is `inputWidth * blockSize`, whereas the
* height is `inputHeight * blockSize`
*
* - The Y, X coordinates within each block of the output image are determined
* by the high order component of the input channel index
*
* - The depth of the input tensor must be divisible by `blockSize *
* blockSize`
*
* The `dataFormat` attr specifies the layout of the input and output tensors
* with the following options: "NHWC": [ `batch, height, width, channels` ]
* "NCHW": [ `batch, channels, height, width` ]
*
* ```js
* const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);
* const blockSize = 2;
* const dataFormat = "NHWC";
*
* tf.depthToSpace(x, blockSize, dataFormat).print();
* ```
*
* @param x The input tensor of rank 4
* @param blockSIze An `int` that is `>= 2`. The size of the spatial block
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to "NHWC"
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function depthToSpace_(x, blockSize, dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'depthToSpace');
const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];
const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];
const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];
assert(inputHeight * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputHeight} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
assert(inputWidth * blockSize >= 0, () => `Negative dimension size caused by overflow when multiplying
${inputWidth} and ${blockSize} for depthToSpace with input shape
${$x.shape}`);
assert((inputDepth % (blockSize * blockSize) === 0), () => `Dimension size must be evenly divisible by ${blockSize * blockSize} but is ${inputDepth} for depthToSpace with input shape ${$x.shape}`);
const inputs = { x: $x };
const attrs = { blockSize, dataFormat };
return ENGINE.runKernel(DepthToSpace, inputs, attrs);
}
const depthToSpace = op({ depthToSpace_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Depthwise 2D convolution.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function depthwiseConv2d_(x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'depthwiseConv2d');
const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
assert(x4D.shape[3] === $filter.shape[2], () => `Error in depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in depthwiseConv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dataFormat, dilations, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(DepthwiseConv2dNative, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const depthwiseConv2d = op({ depthwiseConv2d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns a diagonal tensor with a given diagonal values.
*
* Given a diagonal, this operation returns a tensor with the diagonal and
* everything else padded with zeros.
*
* Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor
* of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* tf.diag(x).print()
* ```
* ```js
* const x = tf.tensor1d([1, 2, 3, 4, 5, 6, 6, 8], [4, 2])
*
* tf.diag(x).print()
* ```
* @param x The input tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function diag_(x) {
const $x = convertToTensor(x, 'x', 'diag');
const inputs = { x: $x };
return ENGINE.runKernel(Diag, inputs);
}
const diag = op({ diag_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the grayscale dilation over the input `x`.
*
* @param x The input tensor, rank 3 or rank 4 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filter The filter tensor, rank 3, of shape
* `[filterHeight, filterWidth, depth]`.
* @param strides The strides of the sliding window for each dimension of the
* input tensor: `[strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat Specify the data format of the input and output data.
* Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels].
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`
* is a single number, then `dilationHeight == dilationWidth`. If it is
* greater than 1, then all values of `strides` must be 1.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function dilation2d_(x, filter, strides, pad, dilations = [1, 1], dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'dilation2d');
const $filter = convertToTensor(filter, 'filter', 'dilation2d');
assert($x.rank === 3 || $x.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +
`${$x.rank}.`);
assert($filter.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ` +
`${$filter.rank}.`);
assert(dataFormat === 'NHWC', () => `Error in dilation2d: Only NHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
reshapedTo4D = true;
}
const inputs = { x: x4D, filter: $filter };
const attrs = { strides, pad, dilations };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Dilation2D, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const dilation2d = op({ dilation2d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0
* if denominator is 0.
*
*
* ```js
* const a = tf.tensor1d([1, 4, 9, 16]);
* const b = tf.tensor1d([1, 2, 3, 4]);
* const c = tf.tensor1d([0, 0, 0, 0]);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* ```js
* // Broadcast div a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(2);
* const c = tf.scalar(0);
*
* a.divNoNan(b).print(); // or tf.divNoNan(a, b)
* a.divNoNan(c).print(); // or tf.divNoNan(a, c)
* ```
*
* @param a The first tensor as the numerator.
* @param b The second tensor as the denominator. Must have the same dtype as
* `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function divNoNan_(a, b) {
// TODO: Make this into its own kernel.
let $a = convertToTensor(a, 'a', 'div');
let $b = convertToTensor(b, 'b', 'div');
[$a, $b] = makeTypesMatch($a, $b);
const divResult = div($a, $b);
const zeros = zerosLike(divResult);
const bEqualsZero = equal($b, zeros);
return where(bEqualsZero, zeros, divResult);
}
const divNoNan = op({ divNoNan_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the dot product of two matrices and/or vectors, `t1` and `t2`.
*
* ```js
* const a = tf.tensor1d([1, 2]);
* const b = tf.tensor2d([[1, 2], [3, 4]]);
* const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
*
* a.dot(b).print(); // or tf.dot(a, b)
* b.dot(a).print();
* b.dot(c).print();
* ```
* @param t1 The first tensor in the dot operation.
* @param t2 The second tensor in the dot operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function dot_(t1, t2) {
const $t1 = convertToTensor(t1, 't1', 'dot');
const $t2 = convertToTensor(t2, 't2', 'dot');
assert(($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +
`${$t1.rank} and ${$t2.rank}.`);
const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);
const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);
assert(t1Inner === t2Inner, () => `Error in dot: inner dimensions of inputs must match, but got ` +
`${t1Inner} and ${t2Inner}.`);
if ($t1.rank === 1 && $t2.rank === 1) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, []);
}
else if ($t1.rank === 1 && $t2.rank === 2) {
const t12D = reshape($t1, [1, -1]);
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul(t12D, t22D);
return reshape(t1t2, [t1t2.size]);
}
else if ($t1.rank === 2 && $t2.rank === 1) {
const t22D = reshape($t2, [-1, 1]);
const t1t2 = matMul($t1, t22D);
return reshape(t1t2, [t1t2.size]);
}
else {
const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);
const t1t2 = matMul($t1, t22D);
return t1t2;
}
}
const dot = op({ dot_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Tensor contraction over specified indices and outer product.
*
* `einsum` allows defining Tensors by defining their element-wise computation.
* This computation is based on
* [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).
*
* Some special cases include:
*
* Matrix multiplication:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);
* x.print();
* y.print();
* tf.einsum('ij,jk->ik', x, y).print();
* ```
*
* Dot product:
* ```js
* const x = tf.tensor1d([1, 2, 3]);
* const y = tf.tensor1d([0, 1, 2]);
* x.print();
* y.print();
* tf.einsum('i,i->', x, y).print();
* ```
*
* Batch dot product:
* ```js
* const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);
* const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);
* x.print();
* y.print();
* tf.einsum('bi,bi->b', x, y).print();
* ```
*
* Outer prouduct:
* ```js
* const x = tf.tensor1d([1, 3, 5]);
* const y = tf.tensor1d([2, 4, 6]);
* x.print();
* y.print();
* tf.einsum('i,j->ij', x, y).print();
* ```
*
* Matrix transpose:
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* x.print();
* tf.einsum('ij->ji', x).print();
* ```
*
* Batch matrix transpose:
* ```js
* const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);
* x.print();
* tf.einsum('bij->bji', x).print();
* ```
*
* Limitations:
*
* This implementation of einsum has the following limitations:
*
* - Does not support >2 input tensors.
* - Does not support duplicate axes for any given input tensor. E.g., equation
* 'ii->' is not suppoted.
* - The `...` notation is not supported.
*
* @param equation a string describing the contraction, in the same format as
* [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).
* @param tensors the input(s) to contract (each one a Tensor), whose shapes
* should be consistent with equation.
* @returns The output tensor.
*
* @doc {heading: 'Tensors', subheading: 'Matrices'}
*/
function einsum_(equation, ...tensors) {
const $tensors = tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));
const attrs = { equation };
return ENGINE.runKernel(Einsum, $tensors, attrs);
}
const einsum = op({ einsum_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.
*
* ```js
* const x = tf.tensor1d([-1, 1, -3, 2]);
*
* x.elu().print(); // or tf.elu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function elu_(x) {
const $x = convertToTensor(x, 'x', 'elu');
const inputs = { x: $x };
return ENGINE.runKernel(Elu, inputs);
}
const elu = op({ elu_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes gause error function of the input `tf.Tensor` element-wise:
* `erf(x)`
*
* ```js
* const x = tf.tensor1d([0, .1, -.1, .7]);
*
* x.erf().print(); // or tf.erf(x);
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function erf_(x) {
let $x = convertToTensor(x, 'x', 'erf');
assert($x.dtype === 'int32' || $x.dtype === 'float32', () => 'Input dtype must be `int32` or `float32`.');
if ($x.dtype === 'int32') {
$x = cast($x, 'float32');
}
const inputs = { x: $x };
return ENGINE.runKernel(Erf, inputs);
}
const erf = op({ erf_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes exponential of the input `tf.Tensor` minus one element-wise.
* `e ^ x - 1`
*
* ```js
* const x = tf.tensor1d([1, 2, -3]);
*
* x.expm1().print(); // or tf.expm1(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function expm1_(x) {
const $x = convertToTensor(x, 'x', 'expm1');
const inputs = { x: $x };
return ENGINE.runKernel(Expm1, inputs);
}
const expm1 = op({ expm1_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Create an identity matrix.
*
* @param numRows Number of rows.
* @param numColumns Number of columns. Defaults to `numRows`.
* @param batchShape If provided, will add the batch shape to the beginning
* of the shape of the returned `tf.Tensor` by repeating the identity
* matrix.
* @param dtype Data type.
* @returns Identity matrix of the specified size and data type, possibly
* with batch repetition if `batchShape` is specified.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function eye_(numRows, numColumns, batchShape, dtype = 'float32') {
if (numColumns == null) {
numColumns = numRows;
}
const buff = buffer([numRows, numColumns], dtype);
const n = numRows <= numColumns ? numRows : numColumns;
for (let i = 0; i < n; ++i) {
buff.set(1, i, i);
}
const out = reshape(buff.toTensor(), [numRows, numColumns]);
if (batchShape == null) {
return out;
}
else {
if (batchShape.length === 1) {
return tile(expandDims(out, 0), [batchShape[0], 1, 1]);
}
else if (batchShape.length === 2) {
// tslint:disable-next-line:no-unnecessary-type-assertion
return tile(expandDims(expandDims(out, 0), 0), [batchShape[0], batchShape[1], 1, 1]);
}
else if (batchShape.length === 3) {
// tslint:disable-next-line:no-unnecessary-type-assertion
return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [
batchShape[0], batchShape[1], batchShape[2], 1, 1
]);
}
else {
throw new Error(`eye() currently supports only 1D and 2D ` +
// tslint:disable-next-line:no-any
`batchShapes, but received ${batchShape.length}D.`);
}
}
}
const eye = op({ eye_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` filled with a scalar value.
*
* ```js
* tf.fill([2, 2], 4).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param value The scalar value to fill the tensor with.
* @param dtype The type of an element in the resulting tensor. Defaults to
* 'float'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function fill(shape, value, dtype) {
const attrs = { shape, value, dtype };
return ENGINE.runKernel(Fill, {}, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the imaginary part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the imaginary part of each element in input considered as a complex number.
* If input is real, a tensor of all zeros is returned.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.imag(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function imag_(input) {
const $input = convertToTensor(input, 'input', 'imag');
const inputs = { input: $input };
return ENGINE.runKernel(Imag, inputs);
}
const imag = op({ imag_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Returns which elements of x are finite.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isFinite().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isFinite_(x) {
const $x = convertToTensor(x, 'x', 'isFinite');
const inputs = { x: $x };
return ENGINE.runKernel(IsFinite, inputs);
}
const isFinite$1 = op({ isFinite_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Returns which elements of x are Infinity or -Infinity.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isInf().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isInf_(x) {
const $x = convertToTensor(x, 'x', 'isInf');
const inputs = { x: $x };
return ENGINE.runKernel(IsInf, inputs);
}
const isInf = op({ isInf_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* RReturns which elements of x are NaN.
*
* ```js
* const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);
*
* x.isNaN().print(); // or tf.isNaN(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function isNaN_(x) {
const $x = convertToTensor(x, 'x', 'isNaN');
const inputs = { x: $x };
return ENGINE.runKernel(IsNan, inputs);
}
const isNaN$1 = op({ isNaN_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise.
*
* See
* [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](
* http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.leakyRelu(0.1).print(); // or tf.leakyRelu(x, 0.1)
* ```
* @param x The input tensor.
* @param alpha The scaling factor for negative values, defaults to 0.2.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function leakyRelu_(x, alpha = 0.2) {
const $x = convertToTensor(x, 'x', 'leakyRelu');
const inputs = { x: $x };
const attrs = { alpha };
return ENGINE.runKernel(LeakyRelu, inputs, attrs);
}
const leakyRelu = op({ leakyRelu_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Return an evenly spaced sequence of numbers over the given interval.
*
* ```js
* tf.linspace(0, 9, 10).print();
* ```
* @param start The start value of the sequence.
* @param stop The end value of the sequence.
* @param num The number of values to generate.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function linspace(start, stop, num) {
if (num <= 0) {
throw new Error('The number of values should be positive.');
}
const attrs = { start, stop, num };
return ENGINE.runKernel(LinSpace, {}, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Normalizes the activation of a local neighborhood across or within
* channels.
*
* @param x The input tensor. The 4-D input tensor is treated as a 3-D array
* of 1D vectors (along the last dimension), and each vector is
* normalized independently.
* @param depthRadius The number of adjacent channels in the 1D normalization
* window.
* @param bias A constant bias term for the basis.
* @param alpha A scale factor, usually positive.
* @param beta An exponent.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function localResponseNormalization_(x, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5) {
const $x = convertToTensor(x, 'x', 'localResponseNormalization');
assert($x.rank === 4 || $x.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${$x.rank}.`);
assert(isInt(depthRadius), () => `Error in localResponseNormalization: depthRadius must be an ` +
`integer but got depthRadius ${depthRadius}.`);
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
const inputs = { x: x4D };
const attrs = { depthRadius, bias, alpha, beta };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(LRN, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
else {
return res;
}
}
const localResponseNormalization = op({ localResponseNormalization_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes natural logarithm of the input `tf.Tensor` plus one
* element-wise: `ln(1 + x)`
*
* ```js
* const x = tf.tensor1d([1, 2, Math.E - 1]);
*
* x.log1p().print(); // or tf.log1p(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function log1p_(x) {
const $x = convertToTensor(x, 'x', 'log1p');
const inputs = { x: $x };
return ENGINE.runKernel(Log1p, inputs);
}
const log1p = op({ log1p_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Provided `f(x)`, returns another function `g(x, dy?)`, which gives the
* gradient of `f(x)` with respect to `x`.
*
* If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to
* `x` is computed instead. `f(x)` must take a single tensor `x` and return a
* single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.grad(f);
*
* const x = tf.tensor1d([2, 3]);
* g(x).print();
* ```
*
* ```js
* // f(x) = x ^ 3
* const f = x => x.pow(tf.scalar(3, 'int32'));
* // f'(x) = 3x ^ 2
* const g = tf.grad(f);
* // f''(x) = 6x
* const gg = tf.grad(g);
*
* const x = tf.tensor1d([2, 3]);
* gg(x).print();
* ```
*
* @param f The function f(x), to compute gradient for.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function grad(f) {
assert(isFunction(f), () => 'The f passed in grad(f) must be a function');
return (x, dy) => {
// x can be of any dtype, thus null as the last argument.
const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');
const $dy = (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;
return ENGINE.tidy(() => {
const { value, grads } = ENGINE.gradients(() => f($x), [$x], $dy);
if ($dy != null) {
assertShapesMatch(value.shape, $dy.shape, 'The shape of dy passed in grad(f)(x, dy) must match the shape ' +
'returned by f(x)');
}
checkGrads(grads);
return grads[0];
});
};
}
/**
* Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,
* which gives an array of gradients of `f()` with respect to each input
* [`x1`,`x2`,...].
*
* If `dy` is passed when calling `g()`, the gradient of
* `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.
* The provided `f` must take one or more tensors and return a single tensor
* `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df / da = b, df / db = a
* const g = tf.grads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const [da, db] = g([a, b]);
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*
* @param f The function `f(x1, x2,...)` to compute gradients for.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function grads(f) {
assert(isFunction(f), () => 'The f passed in grads(f) must be a function');
return (args, dy) => {
assert(Array.isArray(args), () => 'The args passed in grads(f)(args) must be an array ' +
'of `Tensor`s or `TensorLike`s');
// args can be of any dtype, thus null as the last argument.
const $args = convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');
const $dy = (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;
return ENGINE.tidy(() => {
const { value, grads } = ENGINE.gradients(() => f(...$args), $args, $dy);
if ($dy != null) {
assertShapesMatch(value.shape, $dy.shape, 'The shape of dy passed in grads(f)([x1,...], dy) must ' +
'match the shape returned by f([x1,...])');
}
checkGrads(grads);
return grads;
});
};
}
/**
* Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grad: The gradient of `f(x)` w.r.t `x` (result of `tf.grad`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(x) = x ^ 2
* const f = x => x.square();
* // f'(x) = 2x
* const g = tf.valueAndGrad(f);
*
* const x = tf.tensor1d([2, 3]);
* const {value, grad} = g(x);
*
* console.log('value');
* value.print();
* console.log('grad');
* grad.print();
* ```
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function valueAndGrad(f) {
assert(isFunction(f), () => 'The f passed in valueAndGrad(f) must be a function');
return (x, dy) => {
assert(x instanceof Tensor, () => 'The x passed in valueAndGrad(f)(x) must be a tensor');
assert(dy == null || dy instanceof Tensor, () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');
const { grads, value } = ENGINE.gradients(() => f(x), [x], dy);
checkGrads(grads);
return { grad: grads[0], value };
};
}
/**
* Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`
* returns a metric you want to show.
*
* The result is a rich object with the following properties:
* - grads: The gradients of `f()` w.r.t each input (result of `tf.grads`).
* - value: The value returned by `f(x)`.
*
* ```js
* // f(a, b) = a * b
* const f = (a, b) => a.mul(b);
* // df/da = b, df/db = a
* const g = tf.valueAndGrads(f);
*
* const a = tf.tensor1d([2, 3]);
* const b = tf.tensor1d([-2, -3]);
* const {value, grads} = g([a, b]);
*
* const [da, db] = grads;
*
* console.log('value');
* value.print();
*
* console.log('da');
* da.print();
* console.log('db');
* db.print();
* ```
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function valueAndGrads(f) {
assert(isFunction(f), () => 'The f passed in valueAndGrads(f) must be a function');
return (args, dy) => {
assert(Array.isArray(args) && args.every(arg => arg instanceof Tensor), () => 'The args passed in valueAndGrads(f)(args) must be array of ' +
'tensors');
assert(dy == null || dy instanceof Tensor, () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');
const res = ENGINE.gradients(() => f(...args), args, dy);
if (dy != null) {
assertShapesMatch(res.value.shape, dy.shape, 'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +
'match the shape returned by f([x1,...])');
}
checkGrads(res.grads);
return res;
};
}
/**
* Computes and returns the gradient of f(x) with respect to the list of
* trainable variables provided by `varList`. If no list is provided, it
* defaults to all trainable variables.
*
* ```js
* const a = tf.variable(tf.tensor1d([3, 4]));
* const b = tf.variable(tf.tensor1d([5, 6]));
* const x = tf.tensor1d([1, 2]);
*
* // f(a, b) = a * x ^ 2 + b * x
* const f = () => a.mul(x.square()).add(b.mul(x)).sum();
* // df/da = x ^ 2, df/db = x
* const {value, grads} = tf.variableGrads(f);
*
* Object.keys(grads).forEach(varName => grads[varName].print());
* ```
*
* @param f The function to execute. f() should return a scalar.
* @param varList The list of variables to compute the gradients with respect
* to. Defaults to all trainable variables.
* @returns An object with the following keys and values:
* - `value`: The value of the function `f`.
* - `grads`: A map from the names of the variables to the gradients.
* If the `varList` argument is provided explicitly and contains a subset of
* non-trainable variables, this map in the return value will contain keys
* that map the names of the non-trainable variables to `null`.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function variableGrads(f, varList) {
assert(isFunction(f), () => 'The f passed in variableGrads(f) must be a function');
assert(varList == null ||
Array.isArray(varList) && varList.every(v => v instanceof Variable), () => 'The varList passed in variableGrads(f, varList) must be an array ' +
'of variables');
const specifiedVarList = varList != null;
if (!specifiedVarList) {
// Get all of the trainable variables.
varList = [];
for (const varName in ENGINE.registeredVariables) {
varList.push(ENGINE.registeredVariables[varName]);
}
}
const specifiedNonTrainable = specifiedVarList ? varList.filter(variable => !variable.trainable) : null;
// Prune non-trainable variables.
const originalVarCount = varList.length;
varList = varList.filter(variable => variable.trainable);
assert(varList.length > 0, () => `variableGrads() expects at least one of the input variables to ` +
`be trainable, but none of the ${originalVarCount} variables is ` +
`trainable.`);
const allowNoGradients = true;
const { value, grads } = ENGINE.gradients(f, varList, null, allowNoGradients);
assert(grads.some(g => g != null), () => 'Cannot find a connection between any variable and the result of ' +
'the loss function y=f(x). Please make sure the operations that ' +
'use variables are inside the function f passed to minimize().');
assert(value.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it ` +
`returned a rank-${value.rank} tensor`);
const namedGrads = {};
varList.forEach((v, i) => {
if (grads[i] != null) {
namedGrads[v.name] = grads[i];
}
});
if (specifiedNonTrainable != null) {
// If varList is explicitly provided and contains non-trainable values,
// add them to the returned gradients with `null` values.
specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);
}
return { value, grads: namedGrads };
}
/**
* Overrides the gradient computation of a function `f`.
*
* Takes a function
* `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`
* and returns another function `g(...inputs)` which takes the same inputs as
* `f`. When called, `g` returns `f().value`. In backward mode, custom gradients
* with respect to each input of `f` are computed using `f().gradFunc`.
*
* The `save` function passsed to `f` should be used for saving tensors needed
* in the gradient. And the `saved` passed to the `gradFunc` is a
* `NamedTensorMap`, which contains those saved tensor.
*
* ```js
* const customOp = tf.customGrad((x, save) => {
* // Save x to make sure it's available later for the gradient.
* save([x]);
* // Override gradient of our custom x ^ 2 op to be dy * abs(x);
* return {
* value: x.square(),
* // Note `saved.x` which points to the `x` we saved earlier.
* gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]
* };
* });
*
* const x = tf.tensor1d([-1, -2, 3]);
* const dx = tf.grad(x => customOp(x));
*
* console.log(`f(x):`);
* customOp(x).print();
* console.log(`f'(x):`);
* dx(x).print();
* ```
*
* @param f The function to evaluate in forward mode, which should return
* `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`
* returns the custom gradients of `f` with respect to its inputs.
*
* @doc {heading: 'Training', subheading: 'Gradients'}
*/
function customGrad(f) {
return ENGINE.customGrad(f);
}
function checkGrads(grads) {
const numNullGradients = grads.filter(g => g == null).length;
if (numNullGradients > 0) {
throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
the f you passed encloses all operations that lead from x to y.`);
}
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.softplus().print(); // or tf.softplus(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function softplus_(x) {
const $x = convertToTensor(x, 'x', 'softplus');
const inputs = { x: $x };
return ENGINE.runKernel(Softplus, inputs);
}
const softplus = op({ softplus_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes log sigmoid of the input `tf.Tensor` element-wise:
* `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.
*
* ```js
* const x = tf.tensor1d([0, 1, -1, .7]);
*
* x.logSigmoid().print(); // or tf.logSigmoid(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function logSigmoid_(x) {
const $x = convertToTensor(x, 'x', 'logSigmoid');
// Use a custom gradient to maintain previous implementation.
// There is no LogSigmoid kernel in TF so we can't use engine.runKernel
// directly
const customOp = customGrad((x) => {
// TODO(yassogba) we can remove the chained softplus call here only
// after backends have modualrized softplus at which point we can call
// engine runKernel(..., Sotfplus, ...) directly.
const value = neg(softplus(neg(x)));
const gradFunc = (dy) => {
const derX = mul(dy, sigmoid(neg(x)));
return derX;
};
return { value, gradFunc };
});
return customOp($x);
}
const logSigmoid = op({ logSigmoid_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the maximum of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and an
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.max().print(); // or tf.max(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.max(axis).print(); // or tf.max(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function max_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'max');
const inputs = { x: $x };
const attrs = { reductionIndices: axis, keepDims };
return ENGINE.runKernel(Max, inputs, attrs);
}
const max = op({ max_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Computes the log softmax.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.logSoftmax().print(); // or tf.logSoftmax(a)
* ```
*
* @param logits The logits array.
* @param axis The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function logSoftmax_(logits, axis = -1) {
const $logits = convertToTensor(logits, 'logits', 'logSoftmax');
if (axis === -1) {
axis = $logits.rank - 1;
}
if (axis !== $logits.rank - 1) {
throw Error('Log Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and axis was ${axis}`);
}
// const forward: ForwardFunc<Tensor> = (backend, save) => {
// const keepDims = true;
// const xMax = max(logits, axis, true);
// const shifted = sub(logits, xMax);
// const value =
// sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,
// keepDims)));
// save([value]);
// return value;
// };
// Use a custom gradient for numerical stability.
const customOp = customGrad((logits, save) => {
const keepDims = true;
const xMax = max(logits, axis, true);
const shifted = sub(logits, xMax);
const value = sub(cast(shifted, 'float32'), log$1(sum$1(exp(shifted), axis, keepDims)));
save([value]);
const gradFunc = (dy, saved) => {
const [value] = saved;
const keepDims = true;
const softmax = exp(value);
return sub(dy, mul(sum$1(dy, axis, keepDims), softmax));
};
return { value, gradFunc };
});
return customOp($logits);
// TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.
// const inputs: LogSoftmaxInputs = {logits: $logits};
// const attrs: LogSoftmaxAttrs = {axis};
// return ENGINE.runKernel(
// LogSoftmax, inputs as {} as NamedTensorMap,
// attrs as {} as NamedAttrMap);
}
const logSoftmax = op({ logSoftmax_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the log(sum(exp(elements across the reduction dimensions)).
*
* Reduces the input along the dimensions given in `axis`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.logSumExp().print(); // or tf.logSumExp(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.logSumExp(axis).print(); // or tf.logSumExp(a, axis)
* ```
* @param x The input tensor.
* @param axis The dimension(s) to reduce. If null (the default),
* reduces all dimensions.
* @param keepDims If true, retains reduced dimensions with length
* of 1. Defaults to false.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function logSumExp_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'logSumExp');
const axes = parseAxisParam(axis, $x.shape);
const xMax = max($x, axes, true /* keepDims */);
const a = sub($x, xMax);
const b = exp(a);
const c = sum$1(b, axes);
const d = log$1(c);
const res = add$1(reshape(xMax, d.shape), d);
if (keepDims) {
const newShape = expandShapeToKeepDim(res.shape, axes);
return reshape(res, newShape);
}
return res;
}
const logSumExp = op({ logSumExp_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of `a OR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalOr(b).print();
* ```
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalOr_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');
const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(LogicalOr, inputs);
}
const logicalOr = op({ logicalOr_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of `a XOR b` element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([false, false, true, true], 'bool');
* const b = tf.tensor1d([false, true, false, true], 'bool');
*
* a.logicalXor(b).print();
* ```
*
* @param a The first input tensor. Must be of dtype bool.
* @param b The second input tensor. Must be of dtype bool.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function logicalXor_(a, b) {
const $a = convertToTensor(a, 'a', 'logicalXor', 'bool');
const $b = convertToTensor(b, 'b', 'logicalXor', 'bool');
assertAndGetBroadcastShape($a.shape, $b.shape);
// x ^ y = (x | y) & ~(x & y)
return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));
}
const logicalXor = op({ logicalXor_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
*/
function maxPool_(x, filterSize, strides, pad, dimRoundingMode) {
const $x = convertToTensor(x, 'x', 'maxPool');
const dilations = 1;
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in maxPool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x4D };
const attrs = { filterSize, strides, pad, dimRoundingMode };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const maxPool = op({ maxPool_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the 3D max pooling.
*
* ```js
* const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);
* const result = tf.maxPool3d(x, 2, 1, 'valid');
* result.print();
* ```
*
* @param x The input tensor, of rank 5 or rank 4 of shape
* `[batch, depth, height, width, inChannels]`.
* @param filterSize The filter size:
* `[filterDepth, filterHeight, filterWidth]`.
* If `filterSize` is a single number,
* then `filterDepth == filterHeight == filterWidth`.
* @param strides The strides of the pooling:
* `[strideDepth, strideHeight, strideWidth]`.
* If `strides` is a single number,
* then `strideDepth == strideHeight == strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1*1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPool3d_(x, filterSize = [1, 1, 1], strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = convertToTensor(x, 'x', 'maxPool3d');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
assert(dataFormat === 'NDHWC', () => `Error in maxPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in maxPool3d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(MaxPool3D, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
}
const maxPool3d = op({ maxPool3d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the 2D max pooling of an image with Argmax index.
* The indices in argmax are flattened, so that a maximum value at position `[b,
* y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if
* include_batch_in_index is False; `((b * height + y) * width + x) * channels
* +c` if include_batch_in_index is True.
*
* The indices returned are always in `[0, height) x [0, width)` before
* flattening.
*
* @param x The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param filterSize The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
* @param dataFormat An optional string from: "NDHWC", "NCDHW". Defaults to
* "NDHWC". Specify the data format of the input and output data. With the
* default format "NDHWC", the data is stored in the order of: [batch,
* depth, height, width, channels]. Only "NDHWC" is currently supported.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param includeBatchIndex Defaults to False. Whether to include batch
* dimension in flattened index of argmax.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function maxPoolWithArgmax_(x, filterSize, strides, pad, includeBatchInIndex = false) {
const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');
const inputs = { x: $x };
const attrs = { filterSize, strides, pad, includeBatchInIndex };
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(MaxPoolWithArgmax, inputs, attrs);
return { result: result[0], indexes: result[1] };
}
const maxPoolWithArgmax = op({ maxPoolWithArgmax_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Computes the mean of elements across dimensions of a `tf.Tensor`.
*
* Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is
* true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with
* a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.mean().print(); // or tf.mean(a)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.mean(axis).print(); // or tf.mean(x, axis)
* ```
*
* @param x The input tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function mean_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'mean');
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Mean, inputs, attrs);
}
const mean = op({ mean_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Broadcasts parameters for evaluation on an N-D grid.
*
* Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`
* of N-D coordinate arrays for evaluating expressions on an N-D grid.
*
* Notes:
* `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.
* When the `indexing` argument is set to 'xy' (the default), the broadcasting
* instructions for the first two dimensions are swapped.
* Examples:
* Calling `const [X, Y] = meshgrid(x, y)` with the tensors
*
* ```javascript
* const x = [1, 2, 3];
* const y = [4, 5, 6];
* const [X, Y] = tf.meshgrid(x, y);
* // X = [[1, 2, 3],
* // [1, 2, 3],
* // [1, 2, 3]]
* // Y = [[4, 4, 4],
* // [5, 5, 5],
* // [6, 6, 6]]
* ```
*
* @param x Tensor with rank geq 1.
* @param y Tensor with rank geq 1.
* @param indexing
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function meshgrid(x, y, { indexing = 'xy' } = {}) {
if (indexing !== 'xy' && indexing !== 'ij') {
throw new TypeError(`${indexing} is not a valid third argument to meshgrid`);
}
if (x === undefined) {
return [];
}
let $x = convertToTensor(x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');
if (y === undefined) {
return [$x];
}
let $y = convertToTensor(y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');
const w = sizeFromShape($x.shape);
const h = sizeFromShape($y.shape);
if (indexing === 'xy') {
$x = reshape($x, [1, -1]);
$y = reshape($y, [-1, 1]);
return [
matMul(ones$1([h, 1], $x.dtype), $x),
matMul($y, ones$1([1, w], $y.dtype)),
];
}
$x = reshape($x, [-1, 1]);
$y = reshape($y, [1, -1]);
return [
matMul($x, ones$1([1, h], $x.dtype)),
matMul(ones$1([w, 1], $y.dtype), $y),
];
}
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Computes the minimum value from the input.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the array is reduced by 1 for each entry in `axes`.
* If `keepDims` is true, the reduced dimensions are retained with length 1.
* If `axes` has no entries, all dimensions are reduced, and an array with a
* single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.min().print(); // or tf.min(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.min(axis).print(); // or tf.min(x, axis)
* ```
*
* @param x The input Tensor.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function min_(x, axis = null, keepDims = false) {
const $x = convertToTensor(x, 'x', 'min');
const inputs = { x: $x };
const attrs = { axis, keepDims };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(Min, inputs, attrs);
}
const min = op({ min_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the min of a and b (`a < b ? a : b`) element-wise.
* Supports broadcasting.
*
* We also expose `minimumStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* ```js
* // Broadcast minimum a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.minimum(b).print(); // or tf.minimum(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function minimum_(a, b) {
let $a = convertToTensor(a, 'a', 'minimum');
let $b = convertToTensor(b, 'b', 'minimum');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'bool') {
$a = cast($a, 'int32');
$b = cast($b, 'int32');
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Minimum, inputs);
}
const minimum = op({ minimum_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Pads a `tf.Tensor` using mirror padding.
*
* This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.
*
* ```js
* const x = tf.range(0, 9).reshape([1, 1, 3, 3]);
* x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();
* ```
* @param x The tensor to pad.
* @param paddings An array of length `R` (the rank of the tensor), where
* each element is a length-2 tuple of ints `[padBefore, padAfter]`,
* specifying how much to pad along each dimension of the tensor.
* In "reflect" mode, the padded regions do not include the borders,
* while in "symmetric" mode the padded regions do include the borders.
* For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,
* then the output is `[1, 2, 3, 2, 1]` in "reflect" mode, and
* `[1, 2, 3, 3, 2]` in "symmetric" mode.
* If `mode` is "reflect" then both `paddings[D, 0]` and `paddings[D, 1]`
* must be no greater than `x.shape[D] - 1`. If mode is "symmetric"
* then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than
* `x.shape[D]`
* @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`
*/
/** @doc {heading: 'Tensors', subheading: 'Transformations'} */
function mirrorPad_(x, paddings, mode) {
assert(mode === 'reflect' || mode === 'symmetric', () => `Invalid mode. Mode must be either reflect or symmetric. ` +
`Got ${mode}.`);
const $x = convertToTensor(x, 'x', 'mirrorPad');
if ($x.rank === 0) {
throw new Error('mirrorPad(scalar) is not defined. ' +
'Pass non-scalar to mirrorPad');
}
assert(paddings.length === $x.rank, () => `Padding doesn't match input. Must be ${$x.rank}. ` +
`Got ${paddings.length}.`);
const shapeOffset = mode === 'reflect' ? 1 : 0;
for (let i = 0; i < $x.rank; i++) {
assert(paddings[i].length === 2, () => `Invalid number of paddings. Must be length of 2 each.`);
assert(paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&
paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset, () => `Padding in dimension ${i} cannot be greater than or equal ` +
`to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +
`shape ${$x.shape}`);
}
const attrs = { paddings, mode };
const inputs = { x: $x };
return ENGINE.runKernel(MirrorPad, inputs, attrs);
}
const mirrorPad = op({ mirrorPad_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the mod of a and b element-wise.
* `floor(x / y) * y + mod(x, y) = x`
* Supports broadcasting.
*
* We also expose `tf.modStrict` which has the same signature as this op and
* asserts that `a` and `b` are the same shape (does not broadcast).
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* ```js
* // Broadcast a mod b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.mod(b).print(); // or tf.mod(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function mod_(a, b) {
let $a = convertToTensor(a, 'a', 'mod');
let $b = convertToTensor(b, 'b', 'mod');
[$a, $b] = makeTypesMatch($a, $b);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Mod, inputs);
}
const mod = op({ mod_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Calculates the mean and variance of `x`. The mean and variance are
* calculated by aggregating the contents of `x` across `axes`. If `x` is
* 1-D and `axes = [0]` this is just the mean and variance of a vector.
*
* @param x The input tensor.
* @param axis The dimension(s) along with to compute mean and
* variance. By default it reduces all dimensions.
* @param keepDims If true, the moments have the same dimensionality as the
* input.
* @return An object with two keys: `mean` and `variance`.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function moments_(x, axis = null, keepDims = false) {
x = convertToTensor(x, 'x', 'moments');
const axes = parseAxisParam(axis, x.shape);
const xMean = mean(x, axes, keepDims);
let keepDimsShape = xMean.shape;
if (!keepDims) {
keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);
}
const devSquared = square(sub(cast(x, 'float32'), reshape(xMean, keepDimsShape)));
const variance = mean(devSquared, axes, keepDims);
return { mean: xMean, variance };
}
const moments = op({ moments_ });
/**
* Computes the next states and outputs of a stack of LSTMCells.
*
* Each cell output is used as input to the next cell.
*
* Returns `[cellState, cellOutput]`.
*
* Derived from tf.contrib.rn.MultiRNNCell.
*
* @param lstmCells Array of LSTMCell functions.
* @param data The input to the cell.
* @param c Array of previous cell states.
* @param h Array of previous cell outputs.
*
* @doc {heading: 'Operations', subheading: 'RNN'}
*/
function multiRNNCell_(lstmCells, data, c, h) {
const $data = convertToTensor(data, 'data', 'multiRNNCell');
const $c = convertToTensorArray(c, 'c', 'multiRNNCell');
const $h = convertToTensorArray(h, 'h', 'multiRNNCell');
let input = $data;
const newStates = [];
for (let i = 0; i < lstmCells.length; i++) {
const output = lstmCells[i](input, $c[i], $h[i]);
newStates.push(output[0]);
newStates.push(output[1]);
input = output[1];
}
const newC = [];
const newH = [];
for (let i = 0; i < newStates.length; i += 2) {
newC.push(newStates[i]);
newH.push(newStates[i + 1]);
}
return [newC, newH];
}
const multiRNNCell = op({ multiRNNCell_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values drawn from a multinomial distribution.
*
* ```js
* const probs = tf.tensor([.75, .25]);
* tf.multinomial(probs, 3).print();
* ```
*
* @param logits 1D array with unnormalized log-probabilities, or
* 2D array of shape `[batchSize, numOutcomes]`. See the `normalized`
* parameter.
* @param numSamples Number of samples to draw for each row slice.
* @param seed The seed number.
* @param normalized Whether the provided `logits` are normalized true
* probabilities (sum to 1). Defaults to false.
* @return 1D array of shape `[numSamples]`, or 2D array of shape
* `[batchSize, numSamples]`, depending on the rank of the input.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function multinomial_(logits, numSamples, seed, normalized = false) {
const $logits = convertToTensor(logits, 'logits', 'multinomial');
const numOutcomes = $logits.size;
const origRank = $logits.rank;
if (numOutcomes < 2) {
throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ` +
`${numOutcomes}.`);
}
if (origRank > 2) {
throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);
}
// TODO(lina128): Investigate correct seed behavior. The code seems not allow
// setting see to 0.
seed = seed || Math.random();
// The kernel only accepts (and returns) rank 2 tensors.
const logits2D = origRank === 1 ? reshape($logits, [1, -1]) : $logits;
const inputs = { logits: logits2D };
const attrs = { numSamples, seed, normalized };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(Multinomial, inputs, attrs);
// tslint:disable-next-line:no-unnecessary-type-assertion
return origRank === 1 ? reshape(res, [res.size]) : res;
}
const multinomial = op({ multinomial_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the truth value of (a != b) element-wise. Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([0, 2, 3]);
*
* a.notEqual(b).print();
* ```
* @param a The first input tensor.
* @param b The second input tensor. Must have the same dtype as `a`.
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
function notEqual_(a, b) {
let $a = convertToTensor(a, 'a', 'notEqual', 'string_or_numeric');
let $b = convertToTensor(b, 'b', 'notEqual', 'string_or_numeric');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(NotEqual, inputs);
}
const notEqual = op({ notEqual_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a one-hot `tf.Tensor`. The locations represented by `indices` take
* value `onValue` (defaults to 1), while all other locations take value
* `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank
* `R+1` with the last axis of size `depth`.
*
* ```js
* tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();
* ```
*
* @param indices `tf.Tensor` of indices with dtype `int32`.
* @param depth The depth of the one hot dimension.
* @param onValue A number used to fill in the output when the index matches
* the location.
* @param offValue A number used to fill in the output when the index does
* not match the location.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function oneHot_(indices, depth, onValue = 1, offValue = 0) {
if (depth < 2) {
throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);
}
const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');
const inputs = { indices: $indices };
const attrs = { depth, onValue, offValue };
return ENGINE.runKernel(OneHot, inputs, attrs);
}
const oneHot = op({ oneHot_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with all elements set to 1 with the same shape as the
* given tensor.
*
* ```js
* const x = tf.tensor([1, 2]);
* tf.onesLike(x).print();
* ```
* @param x A tensor.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function onesLike_(x) {
const $x = convertToTensor(x, 'x', 'onesLike');
const inputs = { x: $x };
return ENGINE.runKernel(OnesLike, inputs);
}
const onesLike = op({ onesLike_ });
/**
* Computes the outer product of two vectors, `v1` and `v2`.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
* const b = tf.tensor1d([3, 4, 5]);
*
* tf.outerProduct(a, b).print();
* ```
* @param v1 The first vector in the outer product operation.
* @param v2 The second vector in the outer product operation.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function outerProduct_(v1, v2) {
const $v1 = convertToTensor(v1, 'v1', 'outerProduct');
const $v2 = convertToTensor(v2, 'v2', 'outerProduct');
assert($v1.rank === 1 && $v2.rank === 1, () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +
`${$v1.rank} and ${$v2.rank}.`);
const v12D = reshape($v1, [-1, 1]);
const v22D = reshape($v2, [1, -1]);
return matMul(v12D, v22D);
}
const outerProduct = op({ outerProduct_ });
/**
* Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.
*/
function pad1d_(x, paddings, constantValue = 0) {
assert(paddings.length === 2, () => 'Invalid number of paddings. Must be length of 2.');
return pad(x, [paddings], constantValue);
}
const pad1d = op({ pad1d_ });
/**
* Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.
*/
function pad2d_(x, paddings, constantValue = 0) {
assert(paddings.length === 2 && paddings[0].length === 2 &&
paddings[1].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad2d = op({ pad2d_ });
/**
* Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.
*/
function pad3d_(x, paddings, constantValue = 0) {
assert(paddings.length === 3 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad3d = op({ pad3d_ });
/**
* Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.
*/
function pad4d_(x, paddings, constantValue = 0) {
assert(paddings.length === 4 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2 &&
paddings[3].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');
return pad(x, paddings, constantValue);
}
const pad4d = op({ pad4d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Performs an N-D pooling operation
*
* @param input The input tensor, of rank 4 or rank 3 of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param windowShape The filter size: `[filterHeight, filterWidth]`. If
* `filterSize` is a single number, then `filterHeight == filterWidth`.
* @param poolingType The type of pooling, either 'max' or 'avg'.
* @param pad The type of padding algorithm:
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_guides/python/nn#Convolution](
* https://www.tensorflow.org/api_guides/python/nn#Convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If
* `strides` is a single number, then `strideHeight == strideWidth`.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function pool_(input, windowShape, poolingType, pad, dilations, strides) {
if (dilations == null) {
dilations = [1, 1];
}
if (strides == null) {
strides = 1;
}
if (pad === 0) {
pad = 'valid';
}
const $x = convertToTensor(input, 'x', 'maxPool');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in pool: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
const convInfo = computePool2DInfo(x4D.shape, windowShape, strides, dilations, pad);
const dilation = [convInfo.dilationHeight, convInfo.dilationWidth];
// The following implementation does batchToSpace(pool(spaceToBatch(x)))
// whenever dilation > 1 since the TF kernels do not support dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037
let basePadding;
if (pad === 'same') {
basePadding = withSpaceToBatchBasePaddings([convInfo.filterHeight, convInfo.filterWidth], dilation);
}
else {
basePadding = [[0, 0], [0, 0]];
}
const isDilationOne = dilation[0] === 1 && dilation[1] === 1;
const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings([convInfo.inHeight, convInfo.inWidth], dilation, basePadding);
const convertedPad = isDilationOne ? pad : 'valid';
const convertedX = isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);
const forwardOp = poolingType === 'avg' ?
() => avgPool(convertedX, windowShape, strides, convertedPad) :
() => maxPool(convertedX, windowShape, strides, convertedPad);
const y = forwardOp();
const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
// Helper function to compute crops and paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184
function requiredSpaceToBatchPaddings(inputShape, blockShape, basePadding) {
const padStart = basePadding.map(b => b[0]);
const origPadEnd = basePadding.map(b => b[1]);
const fullInputShape = inputShape.concat(padStart, origPadEnd);
const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);
const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);
const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);
const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);
return [paddings, crops];
}
// Helper function to compute base paddings for pool with dilation > 1.
// tslint:disable-next-line:max-line-length
// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524
function withSpaceToBatchBasePaddings(filterShape, dilation) {
// Spatial dimensions of the filters and the upsampled filters in which we
// introduce (rate - 1) zeros between consecutive filter values.
const dilatedFilterShape = filterShape.map((s, i) => {
return s + (s - 1) * (dilation[i] - 1);
});
const padExtraShape = dilatedFilterShape.map(s => s - 1);
// When padding is odd, we pad more at end, following the same
// convention as conv2d.
const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));
const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);
return padExtraShape.map((_, i) => {
return [padExtraStart[i], padExtraEnd[i]];
});
}
const pool = op({ pool_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes leaky rectified linear element-wise with parametric alphas.
*
* `x < 0 ? alpha * x : f(x) = x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
* const alpha = tf.scalar(0.1);
*
* x.prelu(alpha).print(); // or tf.prelu(x, alpha)
* ```
* @param x The input tensor.
* @param alpha Scaling factor for negative values.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function prelu_(x, alpha) {
const $x = convertToTensor(x, 'x', 'prelu');
const $alpha = convertToTensor(alpha, 'alpha', 'prelu');
const inputs = { x: $x, alpha: $alpha };
return ENGINE.runKernel(Prelu, inputs);
}
const prelu = op({ prelu_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Prints information about the `tf.Tensor` including its data.
*
* ```js
* const verbose = true;
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);
* ```
* @param x The tensor to be printed.
* @param verbose Whether to print verbose information about the ` Tensor`,
* including dtype and size.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function print(x, verbose = false) {
console.log(x.toString(verbose));
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the product of elements across dimensions of a `tf.Tensor`.
*
* Reduces the input along the dimensions given in `axes`. Unless `keepDims`
* is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in
* `axes`. If `keepDims` is true, the reduced dimensions are retained with
* length 1. If `axes` has no entries, all dimensions are reduced, and a
* `tf.Tensor` with a single element is returned.
*
* ```js
* const x = tf.tensor1d([1, 2, 3]);
*
* x.prod().print(); // or tf.prod(x)
* ```
*
* ```js
* const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);
*
* const axis = 1;
* x.prod(axis).print(); // or tf.prod(x, axis)
* ```
*
* @param x The input tensor to compute the product over. If the dtype is `bool`
* it will be converted to `int32` and the output dtype will be `int32`.
* @param axis The dimension(s) to reduce. By default it reduces
* all dimensions.
* @param keepDims If true, retains reduced dimensions with size 1.
*
* @doc {heading: 'Operations', subheading: 'Reduction'}
*/
function prod_(x, axis = null, keepDims = false) {
let $x = convertToTensor(x, 'x', 'prod');
if ($x.dtype === 'bool') {
// bool is not an allowed type for the underlying kernel.
$x = cast($x, 'int32');
}
const inputs = { x: $x };
const attrs = { axis, keepDims };
return ENGINE.runKernel(Prod, inputs, attrs);
}
const prod = op({ prod_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a random number generator
* function defined by the user.
*
* @param shape An array of integers defining the output tensor shape.
* @param randFunction A random number generator function which is called
* for each element in the output tensor.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function rand_(shape, randFunction, dtype) {
const size = sizeFromShape(shape);
let values = null;
if (dtype == null || dtype === 'float32') {
values = new Float32Array(size);
}
else if (dtype === 'int32') {
values = new Int32Array(size);
}
else if (dtype === 'bool') {
values = new Uint8Array(size);
}
else {
throw new Error(`Unknown data type ${dtype}`);
}
for (let i = 0; i < size; i++) {
values[i] = randFunction();
}
return ENGINE.makeTensor(values, shape, dtype);
}
const rand = op({ rand_ });
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var alea = createCommonjsModule(function (module) {
// A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010
// http://baagoe.com/en/RandomMusings/javascript/
// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
// Original work is under MIT license -
// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>
//
// 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.
(function(global, module, define) {
function Alea(seed) {
var me = this, mash = Mash();
me.next = function() {
var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32
me.s0 = me.s1;
me.s1 = me.s2;
return me.s2 = t - (me.c = t | 0);
};
// Apply the seeding algorithm from Baagoe.
me.c = 1;
me.s0 = mash(' ');
me.s1 = mash(' ');
me.s2 = mash(' ');
me.s0 -= mash(seed);
if (me.s0 < 0) { me.s0 += 1; }
me.s1 -= mash(seed);
if (me.s1 < 0) { me.s1 += 1; }
me.s2 -= mash(seed);
if (me.s2 < 0) { me.s2 += 1; }
mash = null;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function impl(seed, opts) {
var xg = new Alea(seed),
state = opts && opts.state,
prng = xg.next;
prng.int32 = function() { return (xg.next() * 0x100000000) | 0; };
prng.double = function() {
return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.alea = impl;
}
})(
commonjsGlobal,
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var xor128 = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xor128" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
// Set up generator function.
me.next = function() {
var t = me.x ^ (me.x << 11);
me.x = me.y;
me.y = me.z;
me.z = me.w;
return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);
};
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xor128 = impl;
}
})(
commonjsGlobal,
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var xorwow = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xorwow" prng algorithm by
// George Marsaglia. See http://www.jstatsoft.org/v08/i14/paper
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var t = (me.x ^ (me.x >>> 2));
me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;
return (me.d = (me.d + 362437 | 0)) +
(me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;
};
me.x = 0;
me.y = 0;
me.z = 0;
me.w = 0;
me.v = 0;
if (seed === (seed | 0)) {
// Integer seed.
me.x = seed;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 64; k++) {
me.x ^= strseed.charCodeAt(k) | 0;
if (k == strseed.length) {
me.d = me.x << 10 ^ me.x >>> 4;
}
me.next();
}
}
function copy(f, t) {
t.x = f.x;
t.y = f.y;
t.z = f.z;
t.w = f.w;
t.v = f.v;
t.d = f.d;
return t;
}
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xorwow = impl;
}
})(
commonjsGlobal,
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var xorshift7 = createCommonjsModule(function (module) {
// A Javascript implementaion of the "xorshift7" algorithm by
// François Panneton and Pierre L'ecuyer:
// "On the Xorgshift Random Number Generators"
// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
// Update xor generator.
var X = me.x, i = me.i, t, v, w;
t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);
t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);
t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);
t = X[(i + 4) & 7]; v ^= t ^ (t << 7);
t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);
X[i] = v;
me.i = (i + 1) & 7;
return v;
};
function init(me, seed) {
var j, w, X = [];
if (seed === (seed | 0)) {
// Seed state array using a 32-bit integer.
w = X[0] = seed;
} else {
// Seed state using a string.
seed = '' + seed;
for (j = 0; j < seed.length; ++j) {
X[j & 7] = (X[j & 7] << 15) ^
(seed.charCodeAt(j) + X[(j + 1) & 7] << 13);
}
}
// Enforce an array length of 8, not all zeroes.
while (X.length < 8) X.push(0);
for (j = 0; j < 8 && X[j] === 0; ++j);
if (j == 8) w = X[7] = -1; else w = X[j];
me.x = X;
me.i = 0;
// Discard an initial 256 values.
for (j = 256; j > 0; --j) {
me.next();
}
}
init(me, seed);
}
function copy(f, t) {
t.x = f.x.slice();
t.i = f.i;
return t;
}
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.x) copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xorshift7 = impl;
}
})(
commonjsGlobal,
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var xor4096 = createCommonjsModule(function (module) {
// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.
//
// This fast non-cryptographic random number generator is designed for
// use in Monte-Carlo algorithms. It combines a long-period xorshift
// generator with a Weyl generator, and it passes all common batteries
// of stasticial tests for randomness while consuming only a few nanoseconds
// for each prng generated. For background on the generator, see Brent's
// paper: "Some long-period random number generators using shifts and xors."
// http://arxiv.org/pdf/1004.3115v1.pdf
//
// Usage:
//
// var xor4096 = require('xor4096');
// random = xor4096(1); // Seed with int32 or string.
// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.
// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.
//
// For nonzero numeric keys, this impelementation provides a sequence
// identical to that by Brent's xorgens 3 implementaion in C. This
// implementation also provides for initalizing the generator with
// string seeds, or for saving and restoring the state of the generator.
//
// On Chrome, this prng benchmarks about 2.1 times slower than
// Javascript's built-in Math.random().
(function(global, module, define) {
function XorGen(seed) {
var me = this;
// Set up generator function.
me.next = function() {
var w = me.w,
X = me.X, i = me.i, t, v;
// Update Weyl generator.
me.w = w = (w + 0x61c88647) | 0;
// Update xor generator.
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
// Update Xor generator array state.
v = X[i] = v ^ t;
me.i = i;
// Result is the combination.
return (v + (w ^ (w >>> 16))) | 0;
};
function init(me, seed) {
var t, v, i, j, w, X = [], limit = 128;
if (seed === (seed | 0)) {
// Numeric seeds initialize v, which is used to generates X.
v = seed;
seed = null;
} else {
// String seeds are mixed into v and X one character at a time.
seed = seed + '\0';
v = 0;
limit = Math.max(limit, seed.length);
}
// Initialize circular array and weyl value.
for (i = 0, j = -32; j < limit; ++j) {
// Put the unicode characters into the array, and shuffle them.
if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);
// After 32 shuffles, take v as the starting w value.
if (j === 0) w = v;
v ^= v << 10;
v ^= v >>> 15;
v ^= v << 4;
v ^= v >>> 13;
if (j >= 0) {
w = (w + 0x61c88647) | 0; // Weyl.
t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.
i = (0 == t) ? i + 1 : 0; // Count zeroes.
}
}
// We have detected all zeroes; make the key nonzero.
if (i >= 128) {
X[(seed && seed.length || 0) & 127] = -1;
}
// Run the generator 512 times to further mix the state before using it.
// Factoring this as a function slows the main generator, so it is just
// unrolled here. The weyl generator is not advanced while warming up.
i = 127;
for (j = 4 * 128; j > 0; --j) {
v = X[(i + 34) & 127];
t = X[i = ((i + 1) & 127)];
v ^= v << 13;
t ^= t << 17;
v ^= v >>> 15;
t ^= t >>> 12;
X[i] = v ^ t;
}
// Storing state as object members is faster than using closure variables.
me.w = w;
me.X = X;
me.i = i;
}
init(me, seed);
}
function copy(f, t) {
t.i = f.i;
t.w = f.w;
t.X = f.X.slice();
return t;
};
function impl(seed, opts) {
if (seed == null) seed = +(new Date);
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (state.X) copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.xor4096 = impl;
}
})(
commonjsGlobal, // window object or global
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var tychei = createCommonjsModule(function (module) {
// A Javascript implementaion of the "Tyche-i" prng algorithm by
// Samuel Neves and Filipe Araujo.
// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
(function(global, module, define) {
function XorGen(seed) {
var me = this, strseed = '';
// Set up generator function.
me.next = function() {
var b = me.b, c = me.c, d = me.d, a = me.a;
b = (b << 25) ^ (b >>> 7) ^ c;
c = (c - d) | 0;
d = (d << 24) ^ (d >>> 8) ^ a;
a = (a - b) | 0;
me.b = b = (b << 20) ^ (b >>> 12) ^ c;
me.c = c = (c - d) | 0;
me.d = (d << 16) ^ (c >>> 16) ^ a;
return me.a = (a - b) | 0;
};
/* The following is non-inverted tyche, which has better internal
* bit diffusion, but which is about 25% slower than tyche-i in JS.
me.next = function() {
var a = me.a, b = me.b, c = me.c, d = me.d;
a = (me.a + me.b | 0) >>> 0;
d = me.d ^ a; d = d << 16 ^ d >>> 16;
c = me.c + d | 0;
b = me.b ^ c; b = b << 12 ^ d >>> 20;
me.a = a = a + b | 0;
d = d ^ a; me.d = d = d << 8 ^ d >>> 24;
me.c = c = c + d | 0;
b = b ^ c;
return me.b = (b << 7 ^ b >>> 25);
}
*/
me.a = 0;
me.b = 0;
me.c = 2654435769 | 0;
me.d = 1367130551;
if (seed === Math.floor(seed)) {
// Integer seed.
me.a = (seed / 0x100000000) | 0;
me.b = seed | 0;
} else {
// String seed.
strseed += seed;
}
// Mix in string seed, then discard an initial batch of 64 values.
for (var k = 0; k < strseed.length + 20; k++) {
me.b ^= strseed.charCodeAt(k) | 0;
me.next();
}
}
function copy(f, t) {
t.a = f.a;
t.b = f.b;
t.c = f.c;
t.d = f.d;
return t;
};
function impl(seed, opts) {
var xg = new XorGen(seed),
state = opts && opts.state,
prng = function() { return (xg.next() >>> 0) / 0x100000000; };
prng.double = function() {
do {
var top = xg.next() >>> 11,
bot = (xg.next() >>> 0) / 0x100000000,
result = (top + bot) / (1 << 21);
} while (result === 0);
return result;
};
prng.int32 = xg.next;
prng.quick = prng;
if (state) {
if (typeof(state) == 'object') copy(state, xg);
prng.state = function() { return copy(xg, {}); };
}
return prng;
}
if (module && module.exports) {
module.exports = impl;
} else if (define && define.amd) {
define(function() { return impl; });
} else {
this.tychei = impl;
}
})(
commonjsGlobal,
('object') == 'object' && module, // present in node.js
(typeof undefined) == 'function' && undefined // present with an AMD loader
);
});
var seedrandom = createCommonjsModule(function (module) {
/*
Copyright 2014 David Bau.
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.
*/
(function (pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
var global = this,
width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
startdenom = math.pow(width, chunks),
significance = math.pow(2, digits),
overflow = significance * 2,
mask = width - 1,
nodecrypto; // node.js crypto module, initialized at the bottom.
//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
var key = [];
options = (options == true) ? { entropy: true } : (options || {});
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
options.entropy ? [seed, tostring(pool)] :
(seed == null) ? autoseed() : seed, 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
var prng = function() {
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
prng.int32 = function() { return arc4.g(4) | 0; };
prng.quick = function() { return arc4.g(4) / 0x100000000; };
prng.double = prng;
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Calling convention: what to return as a function of prng, seed, is_math.
return (options.pass || callback ||
function(prng, seed, is_math_call, state) {
if (state) {
// Load the arc4 state from the given state if it has an S array.
if (state.S) { copy(state, arc4); }
// Only provide the .state method if requested via options.state.
prng.state = function() { return copy(arc4, {}); };
}
// If called as a method of Math (Math.seedrandom()), mutate
// Math.random because that is how seedrandom.js has worked since v1.0.
if (is_math_call) { math[rngname] = prng; return seed; }
// Otherwise, it is a newer calling convention, so return the
// prng directly.
else return prng;
})(
prng,
shortseed,
'global' in options ? options.global : (this == math),
options.state);
}
math['seed' + rngname] = seedrandom;
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability, the function call below automatically
// discards an initial batch of values. This is called RC4-drop[256].
// See http://google.com/search?q=rsa+fluhrer+response&btnI
})(width);
}
//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
};
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj), prop;
if (depth && typ == 'object') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 'string' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
try {
var out;
if (nodecrypto && (out = nodecrypto.randomBytes)) {
// The use of 'out' to remember randomBytes makes tight minified code.
out = out(width);
} else {
out = new Uint8Array(width);
(global.crypto || global.msCrypto).getRandomValues(out);
}
return tostring(out);
} catch (e) {
var browser = global.navigator,
plugins = browser && browser.plugins;
return [+new Date, global, plugins, global.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
if (('object') == 'object' && module.exports) {
module.exports = seedrandom;
// When in node.js, try using crypto package for autoseeding.
try {
nodecrypto = require('crypto');
} catch (ex) {}
} else if ((typeof undefined) == 'function' && undefined.amd) {
undefined(function() { return seedrandom; });
}
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
Math // math: package containing random, pow, and seedrandom
);
});
// A library of seedable RNGs implemented in Javascript.
//
// Usage:
//
// var seedrandom = require('seedrandom');
// var random = seedrandom(1); // or any seed.
// var x = random(); // 0 <= x < 1. Every bit is random.
// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.
// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.
// Period: ~2^116
// Reported to pass all BigCrush tests.
// xor128, a pure xor-shift generator by George Marsaglia.
// Period: 2^128-1.
// Reported to fail: MatrixRank and LinearComp.
// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.
// Period: 2^192-2^32
// Reported to fail: CollisionOver, SimpPoker, and LinearComp.
// xorshift7, by François Panneton and Pierre L'ecuyer, takes
// a different approach: it adds robustness by allowing more shifts
// than Marsaglia's original three. It is a 7-shift generator
// with 256 bits, that passes BigCrush with no systmatic failures.
// Period 2^256-1.
// No systematic BigCrush failures reported.
// xor4096, by Richard Brent, is a 4096-bit xor-shift with a
// very long period that also adds a Weyl generator. It also passes
// BigCrush with no systematic failures. Its long period may
// be useful if you have many generators and need to avoid
// collisions.
// Period: 2^4128-2^32.
// No systematic BigCrush failures reported.
// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random
// number generator derived from ChaCha, a modern stream cipher.
// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf
// Period: ~2^127
// No systematic BigCrush failures reported.
// The original ARC4-based prng included in this library.
// Period: ~2^1600
seedrandom.alea = alea;
seedrandom.xor128 = xor128;
seedrandom.xorwow = xorwow;
seedrandom.xorshift7 = xorshift7;
seedrandom.xor4096 = xor4096;
seedrandom.tychei = tychei;
var seedrandom$1 = seedrandom;
var seedrandom_1 = seedrandom$1.alea;
/**
* @license
* Copyright 2017 Google LLC. 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.
* =============================================================================
*/
const TEST_EPSILON_FLOAT32 = 1e-3;
const TEST_EPSILON_FLOAT16 = 1e-1;
function expectArraysClose(actual, expected, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, epsilon));
}
function testEpsilon() {
return ENGINE.backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 :
TEST_EPSILON_FLOAT16;
}
function expectArraysPredicate(actual, expected, predicate) {
let checkClassType = true;
if (isTypedArray(actual) || isTypedArray(expected)) {
checkClassType = false;
}
if (isTypedArray(actual) && isTypedArray(expected)) {
checkClassType = true;
}
if (checkClassType) {
const aType = actual.constructor.name;
const bType = expected.constructor.name;
if (aType !== bType) {
throw new Error(`Arrays are of different type. Actual: ${aType}. ` +
`Expected: ${bType}`);
}
}
if (Array.isArray(actual) && Array.isArray(expected)) {
const actualShape = inferShape(actual);
const expectedShape = inferShape(expected);
if (!arraysEqual(actualShape, expectedShape)) {
throw new Error(`Arrays have different shapes. ` +
`Actual: [${actualShape}]. Expected: [${expectedShape}]`);
}
}
const actualFlat = isTypedArray(actual) ? actual : flatten(actual);
const expectedFlat = isTypedArray(expected) ?
expected :
flatten(expected);
if (actualFlat.length !== expectedFlat.length) {
throw new Error(`Arrays have different lengths actual: ${actualFlat.length} vs ` +
`expected: ${expectedFlat.length}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
for (let i = 0; i < expectedFlat.length; ++i) {
const a = actualFlat[i];
const e = expectedFlat[i];
if (!predicate(a, e)) {
throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\n` +
`Actual: ${actualFlat}.\n` +
`Expected: ${expectedFlat}.`);
}
}
}
function expectPromiseToFail(fn, done) {
fn().then(() => done.fail(), () => done());
}
function expectArraysEqual(actual, expected) {
const exp = typeof expected === 'string' || typeof expected === 'number' ||
typeof expected === 'boolean' ?
[expected] :
expected;
if (isString(actual) || isString(actual[0]) ||
isString(expected) || isString(expected[0])) {
// tslint:disable-next-line: triple-equals
return expectArraysPredicate(actual, exp, (a, b) => a == b);
}
return expectArraysPredicate(actual, expected, (a, b) => areClose(a, b, 0));
}
function expectNumbersClose(a, e, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
if (!areClose(a, e, epsilon)) {
throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);
}
}
function areClose(a, e, epsilon) {
if (!isFinite(a) && !isFinite(e)) {
return true;
}
if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {
return false;
}
return true;
}
function expectValuesInRange(actual, low, high) {
for (let i = 0; i < actual.length; i++) {
if (actual[i] < low || actual[i] > high) {
throw new Error(`Value out of range:${actual[i]} low: ${low}, high: ${high}`);
}
}
}
function expectArrayBuffersEqual(actual, expected) {
// Safari & Jasmine don't like comparing ArrayBuffers directly. Wrapping in
// a Float32Array solves this issue.
expect(new Float32Array(actual)).toEqual(new Float32Array(expected));
}
/** Encodes strings into utf-8 bytes. */
function encodeStrings(a) {
for (let i = 0; i < a.length; i++) {
const val = a[i];
if (Array.isArray(val)) {
encodeStrings(val);
}
else {
a[i] = encodeString(val);
}
}
return a;
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
// https://en.wikipedia.org/wiki/Marsaglia_polar_method
class MPRandGauss {
constructor(mean, stdDeviation, dtype, truncated, seed) {
this.mean = mean;
this.stdDev = stdDeviation;
this.dtype = dtype;
this.nextVal = NaN;
this.truncated = truncated;
if (this.truncated) {
this.upper = this.mean + this.stdDev * 2;
this.lower = this.mean - this.stdDev * 2;
}
const seedValue = seed ? seed : Math.random();
this.random = seedrandom_1(seedValue.toString());
}
/** Returns next sample from a Gaussian distribution. */
nextValue() {
if (!isNaN(this.nextVal)) {
const value = this.nextVal;
this.nextVal = NaN;
return value;
}
let resultX, resultY;
let isValid = false;
while (!isValid) {
let v1, v2, s;
do {
v1 = 2 * this.random() - 1;
v2 = 2 * this.random() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s === 0);
const mul = Math.sqrt(-2.0 * Math.log(s) / s);
resultX = this.mean + this.stdDev * v1 * mul;
resultY = this.mean + this.stdDev * v2 * mul;
if (!this.truncated || this.isValidTruncated(resultX)) {
isValid = true;
}
}
if (!this.truncated || this.isValidTruncated(resultY)) {
this.nextVal = this.convertValue(resultY);
}
return this.convertValue(resultX);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype == null || this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
/** Returns true if less than 2-standard-deviations from the mean. */
isValidTruncated(value) {
return value <= this.upper && value >= this.lower;
}
}
// Marsaglia, George, and Wai Wan Tsang. 2000. "A Simple Method for Generating
// Gamma Variables."
class RandGamma {
constructor(alpha, beta, dtype, seed) {
this.alpha = alpha;
this.beta = 1 / beta; // convert rate to scale parameter
this.dtype = dtype;
const seedValue = seed ? seed : Math.random();
this.randu = seedrandom_1(seedValue.toString());
this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());
if (alpha < 1) {
this.d = alpha + (2 / 3);
}
else {
this.d = alpha - (1 / 3);
}
this.c = 1 / Math.sqrt(9 * this.d);
}
/** Returns next sample from a gamma distribution. */
nextValue() {
let x2, v0, v1, x, u, v;
while (true) {
do {
x = this.randn.nextValue();
v = 1 + (this.c * x);
} while (v <= 0);
v *= v * v;
x2 = x * x;
v0 = 1 - (0.331 * x2 * x2);
v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));
u = this.randu();
if (u < v0 || Math.log(u) < v1) {
break;
}
}
v = (1 / this.beta) * this.d * v;
if (this.alpha < 1) {
v *= Math.pow(this.randu(), 1 / this.alpha);
}
return this.convertValue(v);
}
/** Handles proper rounding for non-floating-point numbers. */
convertValue(value) {
if (this.dtype === 'float32') {
return value;
}
return Math.round(value);
}
}
class UniformRandom {
constructor(min = 0, max = 1, dtype, seed) {
/** Handles proper rounding for non floating point numbers. */
this.canReturnFloat = () => (this.dtype == null || this.dtype === 'float32');
this.min = min;
this.range = max - min;
this.dtype = dtype;
if (seed == null) {
seed = Math.random();
}
if (typeof seed === 'number') {
seed = seed.toString();
}
if (!this.canReturnFloat() && this.range <= 1) {
throw new Error(`The difference between ${min} - ${max} <= 1 and dtype is not float`);
}
this.random = seedrandom_1(seed);
}
convertValue(value) {
if (this.canReturnFloat()) {
return value;
}
return Math.round(value);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
}
function jarqueBeraNormalityTest(values) {
// https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
const n = values.length;
const s = skewness(values);
const k = kurtosis(values);
const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));
// JB test requires 2-degress of freedom from Chi-Square @ 0.95:
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
const CHI_SQUARE_2DEG = 5.991;
if (jb > CHI_SQUARE_2DEG) {
throw new Error(`Invalid p-value for JB: ${jb}`);
}
}
function expectArrayInMeanStdRange(actual, expectedMean, expectedStdDev, epsilon) {
if (epsilon == null) {
epsilon = testEpsilon();
}
const actualMean = mean$1(actual);
expectNumbersClose(actualMean, expectedMean, epsilon);
expectNumbersClose(standardDeviation(actual, actualMean), expectedStdDev, epsilon);
}
function mean$1(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
}
return sum / values.length;
}
function standardDeviation(values, mean) {
let squareDiffSum = 0;
for (let i = 0; i < values.length; i++) {
const diff = values[i] - mean;
squareDiffSum += diff * diff;
}
return Math.sqrt(squareDiffSum / values.length);
}
function kurtosis(values) {
// https://en.wikipedia.org/wiki/Kurtosis
const valuesMean = mean$1(values);
const n = values.length;
let sum2 = 0;
let sum4 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum4 += Math.pow(v, 4);
}
return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);
}
function skewness(values) {
// https://en.wikipedia.org/wiki/Skewness
const valuesMean = mean$1(values);
const n = values.length;
let sum2 = 0;
let sum3 = 0;
for (let i = 0; i < n; i++) {
const v = values[i] - valuesMean;
sum2 += Math.pow(v, 2);
sum3 += Math.pow(v, 3);
}
return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a gamma distribution.
*
* ```js
* tf.randomGamma([2, 2], 1).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param alpha The shape parameter of the gamma distribution.
* @param beta The inverse scale parameter of the gamma distribution. Defaults
* to 1.
* @param dtype The data type of the output. Defaults to float32.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomGamma_(shape, alpha, beta = 1, dtype = 'float32', seed) {
if (beta == null) {
beta = 1;
}
if (dtype == null) {
dtype = 'float32';
}
if (dtype !== 'float32' && dtype !== 'int32') {
throw new Error(`Unsupported data type ${dtype}`);
}
const rgamma = new RandGamma(alpha, beta, dtype, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = rgamma.nextValue();
}
return res.toTensor();
}
const randomGamma = op({ randomGamma_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a normal distribution.
*
* ```js
* tf.randomNormal([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type ${dtype}`);
}
const randGauss = new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const randomNormal = op({ randomNormal_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a uniform distribution.
*
* The generated values follow a uniform distribution in the range [minval,
* maxval). The lower bound minval is included in the range, while the upper
* bound maxval is excluded.
*
* ```js
* tf.randomUniform([2, 2]).print();
* ```
*
* @param shape An array of integers defining the output tensor shape.
* @param minval The lower bound on the range of random values to generate.
* Defaults to 0.
* @param maxval The upper bound on the range of random values to generate.
* Defaults to 1.
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Random'}
*/
function randomUniform_(shape, minval = 0, maxval = 1, dtype = 'float32', seed) {
const res = buffer(shape, dtype);
const random = new UniformRandom(minval, maxval, null, seed);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = random.nextValue();
}
return res.toTensor();
}
const randomUniform = op({ randomUniform_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a new `tf.Tensor1D` filled with the numbers in the range provided.
*
* The tensor is a is half-open interval meaning it includes start, but
* excludes stop. Decrementing ranges and negative step values are also
* supported.sv
*
*
* ```js
* tf.range(0, 9, 2).print();
* ```
*
* @param start An integer start value
* @param stop An integer stop value
* @param step An integer increment (will default to 1 or -1)
* @param dtype The data type of the output tensor. Defaults to 'float32'.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function range(start, stop, step = 1, dtype = 'float32') {
if (step === 0) {
throw new Error('Cannot have a step of zero');
}
const attrs = { start, stop, step, dtype };
return ENGINE.runKernel(Range, {} /* inputs */, attrs);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the real part of a complex (or real) tensor.
*
* Given a tensor input, this operation returns a tensor of type float that is
* the real part of each element in input considered as a complex number.
*
* If the input is real, it simply makes a clone.
*
* ```js
* const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);
* tf.real(x).print();
* ```
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function real_(input) {
const $input = convertToTensor(input, 'input', 'real');
const inputs = { input: $input };
return ENGINE.runKernel(Real, inputs);
}
const real = op({ real_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes reciprocal of x element-wise: `1 / x`
*
* ```js
* const x = tf.tensor1d([0, 1, 2]);
*
* x.reciprocal().print(); // or tf.reciprocal(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function reciprocal_(x) {
const $x = convertToTensor(x, 'x', 'reciprocal');
const inputs = { x: $x };
return ENGINE.runKernel(Reciprocal, inputs);
}
const reciprocal = op({ reciprocal_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes rectified linear element-wise: `max(x, 0)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.relu().print(); // or tf.relu(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu_(x) {
const $x = convertToTensor(x, 'x', 'relu');
const inputs = { x: $x };
return ENGINE.runKernel(Relu, inputs);
}
const relu = op({ relu_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 8]);
*
* x.relu6().print(); // or tf.relu6(x)
* ```
* @param x The input tensor. If the dtype is `bool`, the output dtype will be
* `int32'.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function relu6_(x) {
const $x = convertToTensor(x, 'x', 'relu6');
const inputs = { x: $x };
return ENGINE.runKernel(Relu6, inputs);
}
const relu6 = op({ relu6_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor1D`.
*
* @param x The input tensor.
*/
function reverse1d_(x) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 1, () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);
return reverse($x, 0);
}
const reverse1d = op({ reverse1d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor2D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse2d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 2, () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse2d = op({ reverse2d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor3D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse3d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 3, () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse3d = op({ reverse3d_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reverses a `tf.Tensor4D` along a specified axis.
*
* @param x The input tensor.
* @param axis The set of dimensions to reverse. Must be in the
* range [-rank(x), rank(x)). Defaults to all axes.
*/
function reverse4d_(x, axis) {
const $x = convertToTensor(x, 'x', 'reverse');
assert($x.rank === 4, () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);
return reverse($x, axis);
}
const reverse4d = op({ reverse4d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes round of input `tf.Tensor` element-wise: `round(x)`.
* It implements banker's rounding.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3]);
*
* x.round().print(); // or tf.round(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function round_(x) {
const $x = convertToTensor(x, 'x', 'round');
const inputs = { x: $x };
return ENGINE.runKernel(Round, inputs);
}
const round$1 = op({ round_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes scaled exponential linear element-wise.
*
* `x < 0 ? scale * alpha * (exp(x) - 1) : x`
*
* ```js
* const x = tf.tensor1d([-1, 2, -3, 4]);
*
* x.selu().print(); // or tf.selu(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function selu_(x) {
const $x = convertToTensor(x, 'x', 'selu');
const inputs = { x: $x };
return ENGINE.runKernel(Selu, inputs);
}
const selu = op({ selu_ });
/**
* 2-D convolution with separable filters.
*
* Performs a depthwise convolution that acts separately on channels followed
* by a pointwise convolution that mixes channels. Note that this is
* separability between dimensions [1, 2] and 3, not spatial separability
* between dimensions 1 and 2.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)
* for more details.
*
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param depthwiseFilter The depthwise filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is
* the filter used in the first step.
* @param pointwiseFilter The pointwise filter tensor, rank 4, of shape
* `[1, 1, inChannels * channelMultiplier, outChannels]`. This is
* the filter used in the second step.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
*
* @doc {heading: 'Operations', subheading: 'Convolution'}
*/
function separableConv2d_(x, depthwiseFilter, pointwiseFilter, strides, pad, dilation = [1, 1], dataFormat = 'NHWC') {
const $x = convertToTensor(x, 'x', 'separableConv2d');
const $depthwiseFilter = convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');
const $pointwiseFilter = convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
if (dataFormat === 'NCHW') {
throw new Error('separableConv2d currently does not support dataFormat NCHW; only ' +
'NHWC is supported');
}
assert(x4D.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($depthwiseFilter.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
assert($pointwiseFilter.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +
`got rank ${$depthwiseFilter.rank}.`);
assert($pointwiseFilter.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter ` +
` must be 1, but got ${$pointwiseFilter.shape[0]}.`);
assert($pointwiseFilter.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise ` +
`filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);
const inChannels = $depthwiseFilter.shape[2];
const channelMultiplier = $depthwiseFilter.shape[3];
assert($pointwiseFilter.shape[2] === inChannels * channelMultiplier, () => `Error in separableConv2d: the third dimension of pointwise filter ` +
`must be ${inChannels * channelMultiplier}, ` +
`but got ${$pointwiseFilter.shape[2]}.`);
const depthwise = depthwiseConv2d(x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);
const pointwiseStride = 1;
const res = conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const separableConv2d = op({ separableConv2d_ });
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
/**
* Computes the difference between two lists of numbers.
*
* Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`
* that represents all values that are in `x` but not in `y`. The returned
* Tensor `out` is sorted in the same order that the numbers appear in `x`
* (duplicates are preserved). This operation also returns a Tensor indices that
* represents the position of each out element in `x`. In other words:
*
* `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`
*
* ```js
* const x = [1, 2, 3, 4, 5, 6];
* const y = [1, 3, 5];
*
* const [out, indices] = await tf.setdiff1dAsync(x, y);
* out.print(); // [2, 4, 6]
* indices.print(); // [1, 3, 5]
* ```
*
* @param x 1-D Tensor. Values to keep.
* @param y 1-D Tensor. Must have the same type as x. Values to exclude in the
* output.
* @returns Promise of Tensor tuple [out, indices].
* out: Tensor with the same type as x.
* indices: A Tensor of type int32.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
async function setdiff1dAsync_(x, y) {
const $x = convertToTensor(x, 'x', 'setdiff1d');
const $y = convertToTensor(y, 'y', 'setdiff1d');
assert($x.dtype === $y.dtype, () => `x and y should have the same dtype, but got x (${$x.dtype}) and y (${$y.dtype}).`);
assert($x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);
assert($y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);
const xVals = await $x.data();
const yVals = await $y.data();
const ySet = new Set(yVals);
let outputSize = 0;
for (let i = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
outputSize++;
}
}
const buffer = new TensorBuffer([outputSize], $x.dtype);
const indices = new TensorBuffer([outputSize], 'int32');
for (let i = 0, p = 0; i < xVals.length; i++) {
if (!ySet.has(xVals[i])) {
buffer.values[p] = xVals[i];
indices.values[p] = i;
p++;
}
}
return [buffer.toTensor(), indices.toTensor()];
}
const setdiff1dAsync = setdiff1dAsync_;
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Returns an element-wise indication of the sign of a number.
*
* ```js
* const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);
*
* x.sign().print(); // or tf.sign(x)
* ```
* @param x The input Tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function sign_(x) {
const $x = convertToTensor(x, 'x', 'sign');
const inputs = { x: $x };
return ENGINE.runKernel(Sign, inputs);
}
const sign = op({ sign_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a 1D slice from 1D array starting at coordinates `begin` and is
* of length `size`. See `slice` for details.
*/
function slice1d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice1d');
assert($x.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, [begin], [size]);
}
const slice1d = op({ slice1d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a 2D slice from a 2D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice2d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice2d');
assert($x.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice2d = op({ slice2d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a 3D slice from a 3D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice3d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice3d');
assert($x.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice3d = op({ slice3d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a 4D slice from a 4D array starting at coordinates `begin` and
* is of size `size`. See `slice` for details.
*/
function slice4d_(x, begin, size) {
const $x = convertToTensor(x, 'x', 'slice4d');
assert($x.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);
return slice($x, begin, size);
}
const slice4d = op({ slice4d_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the softmax normalized vector given the logits.
*
* ```js
* const a = tf.tensor1d([1, 2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* ```js
* const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);
*
* a.softmax().print(); // or tf.softmax(a)
* ```
*
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function softmax_(logits, dim = -1) {
const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');
if (dim === -1) {
dim = $logits.rank - 1;
}
if (dim !== $logits.rank - 1) {
throw Error('Softmax along a non-last dimension is not yet supported. ' +
`Logits was rank ${$logits.rank} and dim was ${dim}`);
}
const inputs = { logits: $logits };
const attrs = { dim };
return ENGINE.runKernel(Softmax, inputs, attrs);
}
const softmax = op({ softmax_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the inner-most
* dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.fft().print(); // tf.spectral.fft(x).print();
* ```
* @param input The complex input to compute an fft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function fft_(input) {
assert(input.dtype === 'complex64', () => `The dtype for tf.spectral.fft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return ENGINE.runKernel(FFT, inputs);
}
const fft = op({ fft_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Inverse fast Fourier transform.
*
* Computes the inverse 1-dimensional discrete Fourier transform over the
* inner-most dimension of input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([1, 2, 3]);
* const x = tf.complex(real, imag);
*
* x.ifft().print(); // tf.spectral.ifft(x).print();
* ```
* @param input The complex input to compute an ifft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function ifft_(input) {
assert(input.dtype === 'complex64', () => `The dtype for tf.spectral.ifft() must be complex64 ` +
`but got ${input.dtype}.`);
const inputs = { input };
return ENGINE.runKernel(IFFT, inputs);
}
const ifft = op({ ifft_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Inversed real value input fast Fourier transform.
*
* Computes the 1-dimensional inversed discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
* const imag = tf.tensor1d([0, 0, 0]);
* const x = tf.complex(real, imag);
*
* x.irfft().print();
* ```
* @param input The real value input to compute an irfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function irfft_(input) {
const innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let ret;
if (innerDimensionSize <= 2) {
const complexInput = reshape(input, [batch, innerDimensionSize]);
ret = ifft(complexInput);
}
else {
// The length of unique components of the DFT of a real-valued signal
// is 2 * (input_len - 1)
const outputShape = [batch, 2 * (innerDimensionSize - 1)];
const realInput = reshape(real(input), [batch, innerDimensionSize]);
const imagInput = reshape(imag(input), [batch, innerDimensionSize]);
const realConjugate = reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);
const imagConjugate = mul(reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1), scalar(-1));
const r = concat([realInput, realConjugate], 1);
const i = concat([imagInput, imagConjugate], 1);
const complexInput = reshape(complex(r, i), [outputShape[0], outputShape[1]]);
ret = ifft(complexInput);
}
ret = real(ret);
// reshape the result if the input is 3D tensor.
if (input.rank === 3 && input.shape[0] !== 0) {
const temp = ret;
const batch = input.shape[0];
ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);
temp.dispose();
}
return ret;
}
const irfft = op({ irfft_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Real value input fast Fourier transform.
*
* Computes the 1-dimensional discrete Fourier transform over the
* inner-most dimension of the real input.
*
* ```js
* const real = tf.tensor1d([1, 2, 3]);
*
* real.rfft().print();
* ```
* @param input The real value input to compute an rfft over.
*
* @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}
*/
function rfft_(input, fftLength) {
assert(input.dtype === 'float32', () => `The dtype for rfft() must be real value but got ${input.dtype}`);
let innerDimensionSize = input.shape[input.shape.length - 1];
const batch = input.size / innerDimensionSize;
let adjustedInput;
if (fftLength != null && fftLength < innerDimensionSize) {
// Need to crop
const begin = input.shape.map(v => 0);
const size = input.shape.map(v => v);
size[input.shape.length - 1] = fftLength;
adjustedInput = slice(input, begin, size);
innerDimensionSize = fftLength;
}
else if (fftLength != null && fftLength > innerDimensionSize) {
// Need to pad with zeros
const zerosShape = input.shape.map(v => v);
zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;
adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);
innerDimensionSize = fftLength;
}
else {
adjustedInput = input;
}
// Complement the input with zero imaginary numbers.
const zerosInput = zerosLike(adjustedInput);
const complexInput = reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);
const ret = fft(complexInput);
// Exclude complex conjugations. These conjugations are put symmetrically.
const half = Math.floor(innerDimensionSize / 2) + 1;
const realValues = real(ret);
const imagValues = imag(ret);
const realComplexConjugate = split(realValues, [half, innerDimensionSize - half], realValues.shape.length - 1);
const imagComplexConjugate = split(imagValues, [half, innerDimensionSize - half], imagValues.shape.length - 1);
const outputShape = adjustedInput.shape.slice();
outputShape[adjustedInput.shape.length - 1] = half;
return reshape(complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);
}
const rfft = op({ rfft_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns (a - b) * (a - b) element-wise.
* Supports broadcasting.
*
* ```js
* const a = tf.tensor1d([1, 4, 3, 16]);
* const b = tf.tensor1d([1, 2, 9, 4]);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* ```js
* // Broadcast squared difference a with b.
* const a = tf.tensor1d([2, 4, 6, 8]);
* const b = tf.scalar(5);
*
* a.squaredDifference(b).print(); // or tf.squaredDifference(a, b)
* ```
*
* @param a The first tensor.
* @param b The second tensor. Must have the same type as `a`.
*
* @doc {heading: 'Operations', subheading: 'Arithmetic'}
*/
function squaredDifference_(a, b) {
let $a = convertToTensor(a, 'a', 'squaredDifference');
let $b = convertToTensor(b, 'b', 'squaredDifference');
[$a, $b] = makeTypesMatch($a, $b);
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
const attrs = {};
return ENGINE.runKernel(SquaredDifference, inputs, attrs);
}
const squaredDifference = op({ squaredDifference_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Removes dimensions of size 1 from the shape of a `tf.Tensor`.
*
* ```js
* const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);
* x.squeeze().print();
* ```
*
* @param x The input tensor to be squeezed.
* @param axis An optional list of numbers. If specified, only
* squeezes the dimensions listed. The dimension index starts at 0. It
* is an error to squeeze a dimension that is not 1.
*
* @doc {heading: 'Tensors', subheading: 'Transformations'}
*/
function squeeze_(x, axis) {
const $x = convertToTensor(x, 'x', 'squeeze');
return reshape($x, squeezeShape($x.shape, axis).newShape);
}
const squeeze = op({ squeeze_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts a strided slice of a tensor.
*
* Roughly speaking, this op extracts a slice of size (end-begin)/stride from
* the given input tensor (x). Starting at the location specified by begin the
* slice continues by adding stride to the index until all dimensions are not
* less than end. Note that a stride can be negative, which causes a reverse
* slice.
*
* ```js
* const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
* [3, 2, 3]);
* t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print() // [[[3, 3, 3]]]
* t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print() // [[[3, 3, 3],
* // [4, 4, 4]]]
* t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],
* // [3, 3, 3]]]
* ```
*
* @param x The tensor to stride slice.
* @param begin The coordinates to start the slice from.
* @param end: The coordinates to end the slice at.
* @param strides: The size of the slice.
* @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param endMask: If the ith bit of endMask is set, end[i] is ignored
* and the fullest possible range in that dimension is used instead.
* @param shrinkAxisMask: a bitmask where bit i implies that
* the ith specification should shrink the dimensionality. begin and end must
* imply a slice of size 1 in the dimension.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function stridedSlice_(x, begin, end, strides, beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0, shrinkAxisMask = 0) {
const $x = convertToTensor(x, 'x', 'stridedSlice', 'string_or_numeric');
const inputs = { x: $x };
const attrs = {
begin,
end,
strides,
beginMask,
endMask,
ellipsisMask,
newAxisMask,
shrinkAxisMask
};
return ENGINE.runKernel(StridedSlice, inputs, attrs);
}
const stridedSlice = op({ stridedSlice_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes tan of the input `tf.Tensor` element-wise, `tan(x)`
*
* ```js
* const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);
*
* x.tan().print(); // or tf.tan(x)
* ```
* @param x The input tensor.
*
* @doc {heading: 'Operations', subheading: 'Basic math'}
*/
function tan_(x) {
const $x = convertToTensor(x, 'x', 'tan');
const inputs = { x: $x };
return ENGINE.runKernel(Tan, inputs);
}
const tan = op({ tan_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with the provided values, shape and dtype.
*
* ```js
* // Pass an array of values to create a vector.
* tf.tensor([1, 2, 3, 4]).print();
* ```
*
* ```js
* // Pass a nested array of values to make a matrix or a higher
* // dimensional tensor.
* tf.tensor([[1, 2], [3, 4]]).print();
* ```
*
* ```js
* // Pass a flat array and specify a shape yourself.
* tf.tensor([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`. If the values are strings,
* they will be encoded as utf-8 and kept as `Uint8Array[]`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor(values, shape, dtype) {
const inferredShape = inferShape(values, dtype);
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor1d` as it makes the code more readable.
*
* ```js
* tf.tensor1d([1, 2, 3]).print();
* ```
*
* @param values The values of the tensor. Can be array of numbers,
* or a `TypedArray`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor1d(values, dtype) {
assertNonNull(values);
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 1) {
throw new Error('tensor1d() requires values to be a flat/TypedArray');
}
const shape = null;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor2d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor2d([[1, 2], [3, 4]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor2d([1, 2, 3, 4], [2, 2]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor2d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 2) {
throw new Error('tensor2d() requires shape to have two numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 2 && inferredShape.length !== 1) {
throw new Error('tensor2d() requires values to be number[][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor2d() requires shape to be provided when `values` ' +
'are a flat/TypedArray');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor3d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor3d([[[1], [2]], [[3], [4]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. If not provided, it is inferred from
* `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor3d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 3) {
throw new Error('tensor3d() requires shape to have three numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 3 && inferredShape.length !== 1) {
throw new Error('tensor3d() requires values to be number[][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor3d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor4d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor4d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 4) {
throw new Error('tensor4d() requires shape to have four numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 4 && inferredShape.length !== 1) {
throw new Error('tensor4d() requires values to be number[][][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor4d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor5d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor5d([[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor5d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 5) {
throw new Error('tensor5d() requires shape to have five numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 5 && inferredShape.length !== 1) {
throw new Error('tensor5d() requires values to be ' +
'number[][][][][] or flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor5d() requires shape to be provided when `values` ' +
'are a flat array');
}
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.
*
* The same functionality can be achieved with `tf.tensor`, but in general
* we recommend using `tf.tensor6d` as it makes the code more readable.
*
* ```js
* // Pass a nested array.
* tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();
* ```
* ```js
* // Pass a flat array and specify a shape.
* tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();
* ```
*
* @param values The values of the tensor. Can be nested array of numbers,
* or a flat array, or a `TypedArray`.
* @param shape The shape of the tensor. Optional. If not provided,
* it is inferred from `values`.
* @param dtype The data type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function tensor6d(values, shape, dtype) {
assertNonNull(values);
if (shape != null && shape.length !== 6) {
throw new Error('tensor6d() requires shape to have six numbers');
}
const inferredShape = inferShape(values, dtype);
if (inferredShape.length !== 6 && inferredShape.length !== 1) {
throw new Error('tensor6d() requires values to be number[][][][][][] or ' +
'flat/TypedArray');
}
if (inferredShape.length === 1 && shape == null) {
throw new Error('tensor6d() requires shape to be provided when `values` ' +
'are a flat array');
}
shape = shape ||
inferredShape;
return makeTensor(values, shape, inferredShape, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Finds the values and indices of the `k` largest entries along the last
* dimension.
*
* If the input is a vector (rank=1), finds the k largest entries in the vector
* and outputs their values and indices as vectors. Thus values[j] is the j-th
* largest entry in input, and its index is indices[j].
* For higher rank inputs, computes the top k entries along the last dimension.
*
* If two elements are equal, the lower-index element appears first.
*
* ```js
* const a = tf.tensor2d([[1, 5], [4, 3]]);
* const {values, indices} = tf.topk(a);
* values.print();
* indices.print();
* ```
* @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.
* @param k Number of top elements to look for along the last dimension.
* @param sorted If true, the resulting `k` elements will be sorted by the
* values in descending order.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function topk_(x, k = 1, sorted = true) {
const $x = convertToTensor(x, 'x', 'topk');
if ($x.rank === 0) {
throw new Error('topk() expects the input to be of rank 1 or higher');
}
const lastDim = $x.shape[$x.shape.length - 1];
if (k < 0) {
throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);
}
if (k > lastDim) {
throw new Error(`'k' passed to topk() must be <= the last dimension (${lastDim}) ` +
`but got ${k}`);
}
const inputs = { x: $x };
const attrs = { k, sorted };
const [values, indices] = ENGINE.runKernel(TopK, inputs, attrs);
return { values, indices };
}
const topk = op({ topk_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a `tf.Tensor` with values sampled from a truncated normal
* distribution.
*
* ```js
* tf.truncatedNormal([2, 2]).print();
* ```
*
* The generated values follow a normal distribution with specified mean and
* standard deviation, except that values whose magnitude is more than 2
* standard deviations from the mean are dropped and re-picked.
*
* @param shape An array of integers defining the output tensor shape.
* @param mean The mean of the normal distribution.
* @param stdDev The standard deviation of the normal distribution.
* @param dtype The data type of the output tensor.
* @param seed The seed for the random number generator.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function truncatedNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type $ { dtype }`);
}
const randGauss = new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
}
const truncatedNormal = op({ truncatedNormal_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Finds unique elements along an axis of a tensor.
*
* It returns a tensor `values` containing all of the unique elements along the
* `axis` of the given tensor `x` in the same order that they occur along the
* `axis` in `x`; `x` does not need to be sorted. It also returns a tensor
* `indices` the same size as the number of the elements in `x` along the `axis`
* dimension. It contains the index in the unique output `values`.
*
* ```js
* // A 1-D tensor
* const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);
* const {values, indices} = tf.unique(a);
* values.print(); // [1, 2, 4, 7, 8,]
* indices.print(); // [0, 0, 1, 2, 2, 2, 3, 4, 4]
* ```
*
* ```js
* // A 2-D tensor with axis=0
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 0)
* values.print(); // [[1, 0, 0],
* // [2, 0, 0]]
* indices.print(); // [0, 0, 1]
* ```
*
* ```js
* // A 2-D tensor with axis=1
* //
* // 'a' is: [[1, 0, 0],
* // [1, 0, 0],
* // [2, 0, 0]]
* const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);
* const {values, indices} = tf.unique(a, 1)
* values.print(); // [[1, 0],
* // [1, 0],
* // [2, 0]]
* indices.print(); // [0, 1, 1]
* ```
* @param x A tensor (int32, string, bool).
* @param axis The axis of the tensor to find the unique elements.
* @returns [uniqueElements, indices] (see above for details)
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
function unique_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');
assert($x.rank > 0, () => 'The input tensor must be at least 1D');
const inputs = { x: $x };
const attrs = { axis };
const [values, indices] = ENGINE.runKernel(Unique, inputs, attrs);
return { values, indices };
}
const unique = op({ unique_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a new variable with the provided initial value.
* ```js
* const x = tf.variable(tf.tensor([1, 2, 3]));
* x.assign(tf.tensor([4, 5, 6]));
*
* x.print();
* ```
*
* @param initialValue Initial value for the tensor.
* @param trainable If true, optimizers are allowed to update it.
* @param name Name of the variable. Defaults to a unique id.
* @param dtype If set, initialValue will be converted to the given type.
*
* @doc {heading: 'Tensors', subheading: 'Creation'}
*/
function variable(initialValue, trainable = true, name, dtype) {
return ENGINE.makeVariable(initialValue, trainable, name, dtype);
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
function whereImpl(condShape, condVals) {
const indices = [];
for (let i = 0; i < condVals.length; i++) {
if (condVals[i]) {
indices.push(i);
}
}
const inBuffer = buffer(condShape, 'int32');
const out = buffer([indices.length, condShape.length], 'int32');
for (let i = 0; i < indices.length; i++) {
const loc = inBuffer.indexToLoc(indices[i]);
const offset = i * condShape.length;
out.values.set(loc, offset);
}
return out.toTensor();
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Returns the coordinates of true elements of condition.
*
* The coordinates are returned in a 2-D tensor where the first dimension (rows)
* represents the number of true elements, and the second dimension (columns)
* represents the coordinates of the true elements. Keep in mind, the shape of
* the output tensor can vary depending on how many true values there are in
* input. Indices are output in row-major order. The resulting tensor has the
* shape `[numTrueElems, condition.rank]`.
*
* This is analogous to calling the python `tf.where(cond)` without an x or y.
*
* ```js
* const cond = tf.tensor1d([false, false, true], 'bool');
* const result = await tf.whereAsync(cond);
* result.print();
* ```
*
* @doc {heading: 'Operations', subheading: 'Logical'}
*/
async function whereAsync_(condition) {
const $condition = convertToTensor(condition, 'condition', 'whereAsync', 'bool');
const vals = await $condition.data();
const res = whereImpl($condition.shape, vals);
if (condition !== $condition) {
$condition.dispose();
}
return res;
}
const whereAsync = whereAsync_;
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Apply boolean mask to tensor.
*
* ```js
* const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);
* const mask = tf.tensor1d([1, 0, 1], 'bool');
* const result = await tf.booleanMaskAsync(tensor, mask);
* result.print();
* ```
*
* @param tensor N-D tensor.
* @param mask K-D boolean tensor, K <= N and K must be known statically.
* @param axis A 0-D int Tensor representing the axis in tensor to mask from.
* By default, axis is 0 which will mask from the first dimension.
* Otherwise K + axis <= N.
*
* @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}
*/
async function booleanMaskAsync_(tensor, mask, axis) {
const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');
const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');
const axisFrom = axis == null ? 0 : axis;
const maskDim = $mask.rank;
const tensorShape = $tensor.shape;
assert(maskDim > 0, () => 'mask cannot be scalar');
assertShapesMatch(tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape, `mask's shape must match the first K dimensions of tensor's shape,`);
let leadingSize = 1;
for (let i = axisFrom; i < axisFrom + maskDim; i++) {
leadingSize *= tensorShape[i];
}
const targetTensorShape = tensorShape.slice(0, axisFrom)
.concat([leadingSize], tensorShape.slice(axisFrom + maskDim));
const reshapedTensor = reshape($tensor, targetTensorShape);
const reshapedMask = reshape($mask, [-1]);
const positivePositions = await whereAsync(reshapedMask);
const indices = squeeze(positivePositions, [1]);
const res = gather(reshapedTensor, indices, axisFrom);
// Ensure no memory leak.
if (tensor !== $tensor) {
$tensor.dispose();
}
if (mask !== $mask) {
$mask.dispose();
}
indices.dispose();
reshapedTensor.dispose();
reshapedMask.dispose();
positivePositions.dispose();
return res;
}
const booleanMaskAsync = booleanMaskAsync_;
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the norm of scalar, vectors, and matrices.
* This function can compute several different vector norms (the 1-norm, the
* Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)
* and matrix norms (Frobenius, 1-norm, and inf-norm).
*
* ```js
* const x = tf.tensor1d([1, 2, 3, 4]);
*
* x.norm().print(); // or tf.norm(x)
* ```
*
* @param x The input array.
* @param ord Optional. Order of the norm. Supported norm types are
* following:
*
* | ord | norm for matrices | norm for vectors
* |------------|---------------------------|---------------------
* |'euclidean' |Frobenius norm |2-norm
* |'fro' |Frobenius norm |
* |Infinity |max(sum(abs(x), axis=1)) |max(abs(x))
* |-Infinity |min(sum(abs(x), axis=1)) |min(abs(x))
* |1 |max(sum(abs(x), axis=0)) |sum(abs(x))
* |2 | |sum(abs(x)^2)^1/2*
*
* @param axis Optional. If axis is null (the default), the input is
* considered a vector and a single vector norm is computed over the entire
* set of values in the Tensor, i.e. norm(x, ord) is equivalent
* to norm(x.reshape([-1]), ord). If axis is a integer, the input
* is considered a batch of vectors, and axis determines the axis in x
* over which to compute vector norms. If axis is a 2-tuple of integer it is
* considered a batch of matrices and axis determines the axes in NDArray
* over which to compute a matrix norm.
* @param keepDims Optional. If true, the norm have the same dimensionality
* as the input.
*
* @doc {heading: 'Operations', subheading: 'Matrices'}
*/
function norm_(x, ord = 'euclidean', axis = null, keepDims = false) {
x = convertToTensor(x, 'x', 'norm');
const norm = normImpl(x, ord, axis);
let keepDimsShape = norm.shape;
if (keepDims) {
const axes = parseAxisParam(axis, x.shape);
keepDimsShape = expandShapeToKeepDim(norm.shape, axes);
}
return reshape(norm, keepDimsShape);
}
function normImpl(x, p, axis = null) {
if (x.rank === 0) {
return abs(x);
}
// consider vector when no axis is specified
if (x.rank !== 1 && axis === null) {
return normImpl(reshape(x, [-1]), p, axis);
}
// vector
if (x.rank === 1 || typeof axis === 'number' ||
Array.isArray(axis) && axis.length === 1) {
if (p === 1) {
return sum$1(abs(x), axis);
}
if (p === Infinity) {
return max(abs(x), axis);
}
if (p === -Infinity) {
return min(abs(x), axis);
}
if (p === 'euclidean' || p === 2) {
// norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2
return sqrt(sum$1(pow(abs(x), scalar(2, 'int32')), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
// matrix (assumption axis[0] < axis[1])
if (Array.isArray(axis) && axis.length === 2) {
if (p === 1) {
return max(sum$1(abs(x), axis[0]), axis[1] - 1);
}
if (p === Infinity) {
return max(sum$1(abs(x), axis[1]), axis[0]);
}
if (p === -Infinity) {
return min(sum$1(abs(x), axis[1]), axis[0]);
}
if (p === 'fro' || p === 'euclidean') {
// norm(x) = sqrt(sum(pow(x, 2)))
return sqrt(sum$1(square(x), axis));
}
throw new Error(`Error in norm: invalid ord value: ${p}`);
}
throw new Error(`Error in norm: invalid axis: ${axis}`);
}
const norm = op({ norm_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Compute the moving average of a variable.
*
* Without zeroDebias, the moving average operation is defined by:
* `v += delta`
* where
* `delta = (1 - decay) * (x - v)`
*
* With zeroDebias (default), the `delta` term is scaled to debias the
* effect of the (assumed) zero-initialization of `v`.
* `delta /= (1 - decay ^ step)`
*
* For more details on the zero-debiasing algorithm, see:
* https://arxiv.org/abs/1412.6980
*
* Note that this function is completely stateless and does not keep track of
* step count. The step count needs to be maintained by the caller and passed
* in as `step`.
*
* @param v The current moving average value.
* @param x New input value, must have the same shape and dtype as `v`.
* @param decay The decay factor. Typical values are 0.95 and 0.99.
* @param step Step count.
* @param zeroDebias: Whether zeroDebias is to be performed (default: `true`).
* @returns The new moving average value.
*
* @doc {heading: 'Operations', subheading: 'Moving Average'}
*/
function movingAverage_(v, x, decay, step, zeroDebias = true) {
const $v = convertToTensor(v, 'v', 'movingAverage');
const $x = convertToTensor(x, 'x', 'movingAverage');
const $decay = convertToTensor(decay, 'decay', 'movingAverage');
assertTypesMatch($v, $x);
assert(arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');
const one = scalar(1);
const oneMinusDecay = sub(one, $decay);
let update = mul(sub($x, $v), oneMinusDecay);
if (zeroDebias) {
assert(step != null, () => 'When using zeroDebias: true, step is required.');
const $step = convertToTensor(step, 'step', 'movingAverage');
update = div(update, sub(one, pow($decay, $step)));
}
return add$1($v, update);
}
const movingAverage = op({ movingAverage_ });
/**
* Check whether updates.shape = indices.shape[:batchDim] +
* shape[sliceDim:]
*
* @param x The input tensor.
*/
function validateUpdateShape(shape, indices, updates) {
const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;
const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;
const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +
`shape[sliceDim:], got updates.shape: ${updates.shape}` +
`, indices.shape: ${indices.shape}, shape: ${shape}` +
`, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;
if (updates.rank < batchDim) {
throw new Error(shapeError + ` update.rank < ${batchDim}. `);
}
if (shape.length < sliceDim + (updates.rank - batchDim)) {
throw new Error(shapeError +
` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);
}
if (updates.rank !== batchDim + shape.length - sliceDim) {
throw new Error(shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);
}
for (let d = 0; d < batchDim; ++d) {
if (updates.shape[d] !== indices.shape[d]) {
throw new Error(shapeError +
` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${indices.shape[d]}).`);
}
}
for (let d = 0; d < updates.rank - batchDim; ++d) {
if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {
throw new Error(shapeError +
` updates.shape[${d + batchDim}] (${updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${shape[d + batchDim]})`);
}
}
}
/**
* Validate scatter nd inputs.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*/
function validateInput(updates, indices, shape) {
if (indices.rank < 1) {
throw new Error('tf.scatterND() expects the indices to be rank 1 or higher,' +
` but the rank was ${indices.rank}.`);
}
if (updates.rank < 1) {
throw new Error('tf.scatterND() expects the updates to be rank 1 or higher,' +
` but the rank was ${updates.rank}.`);
}
if (indices.dtype !== 'int32') {
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${indices.dtype}`);
}
if (shape.length < 1) {
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${shape}`);
}
if (shape.length === 0) {
if (indices.size === 0) {
throw new Error(`Indices specified for empty output. indices shape: ${indices.shape}`);
}
if (updates.size === 0) {
throw new Error(`Updates specified for empty output. updates shape: ${updates.shape}`);
}
}
validateUpdateShape(shape, indices, updates);
}
/**
* Calculate the shape information for the output.
*
* @param update The tensor contains the update values.
* @param indices The tensor contains the indices for the update values.
* @param shape The shape of the output tensor.
*
* @returns ScatterShapeInfo
*/
function calculateShapes(updates, indices, shape) {
// Calculate the number of dimensions in indices
const indicesRank = indices.shape.length;
const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;
// Calculate the number of elements that make up each slice of our updated
// tensor. This allows us to work with flattened tensors and copy over whole
// slices at a time.
const totalNd = shape.length;
let sliceSize = 1;
for (let i = sliceRank; i < totalNd; ++i) {
sliceSize *= shape[i];
}
const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;
const numUpdates = sizeFromShape(indices.shape) / safeSliceDim;
const strides = [...computeStrides(shape.slice(0, sliceRank)), 1];
const outputSize = sizeFromShape(shape);
return { sliceRank, numUpdates, sliceSize, strides, outputSize };
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Creates a new tensor by applying sparse updates to individual
* values or slices within a zero tensor of the given shape tensor according to
* indices. This operator is the inverse of the `tf.gatherND` operator which
* extracts values or slices from a given tensor.
*
* ```js
* const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');
* const updates = tf.tensor1d([9, 10, 11, 12]);
* const shape = [8];
* tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]
* ```
*
* @param indices The tensor contains the indices into the output tensor.
* @param updates The tensor contains the value for the indices.
* @param shape: The shape of the output tensor.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function scatterND_(indices, updates, shape) {
const $indices = convertToTensor(indices, 'indices', 'scatterND', 'int32');
const $updates = convertToTensor(updates, 'updates', 'scatterND');
validateInput($updates, $indices, shape);
const inputs = { indices: $indices, updates: $updates };
const attrs = { shape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(ScatterNd, inputs, attrs);
}
const scatterND = op({ scatterND_ });
/**
* Validate sparseToDense inputs.
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape number[]. Shape of the dense output tensor.
* @param validateIndices boolean. indice validation is not supported, error
* will be thrown if it is set.
*/
function validateInput$1(sparseIndices, sparseValues, outputShape, defaultValues) {
if (sparseIndices.dtype !== 'int32') {
throw new Error('tf.sparseToDense() expects the indices to be int32 type,' +
` but the dtype was ${sparseIndices.dtype}.`);
}
if (sparseIndices.rank > 2) {
throw new Error('sparseIndices should be a scalar, vector, or matrix,' +
` but got shape ${sparseIndices.shape}.`);
}
const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;
const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;
if (outputShape.length !== numDims) {
throw new Error('outputShape has incorrect number of elements:,' +
` ${outputShape.length}, should be: ${numDims}.`);
}
const numValues = sparseValues.size;
if (!(sparseValues.rank === 0 ||
sparseValues.rank === 1 && numValues === numElems)) {
throw new Error('sparseValues has incorrect shape ' +
`${sparseValues.shape}, should be [] or [${numElems}]`);
}
if (sparseValues.dtype !== defaultValues.dtype) {
throw new Error('sparseValues.dtype must match defaultValues.dtype');
}
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a sparse representation into a dense tensor.
*
* Builds an array dense with shape outputShape such that:
*
* // If sparseIndices is scalar
* dense[i] = (i == sparseIndices ? sparseValues : defaultValue)
*
* // If sparseIndices is a vector, then for each i
* dense[sparseIndices[i]] = sparseValues[i]
*
* // If sparseIndices is an n by d matrix, then for each i in [0, n)
* dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]
* All other values in dense are set to defaultValue. If sparseValues is a
* scalar, all sparse indices are set to this single value.
*
* If indices are repeated the final value is summed over all values for those
* indices.
*
* ```js
* const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');
* const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');
* const shape = [8];
* tf.sparseToDense(indices, values, shape).print();
* ```
*
* @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.
* sparseIndices[i] contains the complete index where sparseValues[i] will be
* placed.
* @param sparseValues A 0-D or 1-D Tensor. Values
* corresponding to each row of sparseIndices, or a scalar value to be used for
* all sparse indices.
* @param outputShape Shape of the dense output tensor. the type is inferred.
* @param defaultValue Scalar. Value to set for indices not specified in
* sparseIndices. Defaults to zero.
*
* @doc {heading: 'Operations', subheading: 'Normalization'}
*/
function sparseToDense_(sparseIndices, sparseValues, outputShape, defaultValue = 0) {
const $sparseIndices = convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');
const $sparseValues = convertToTensor(sparseValues, 'sparseValues', 'sparseToDense');
const $defaultValue = convertToTensor(defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);
validateInput$1($sparseIndices, $sparseValues, outputShape, $defaultValue);
const inputs = {
sparseIndices: $sparseIndices,
sparseValues: $sparseValues,
defaultValue: $defaultValue
};
const attrs = { outputShape };
return ENGINE.runKernel(SparseToDense, inputs, attrs);
}
const sparseToDense = op({ sparseToDense_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Gather slices from input tensor into a Tensor with shape specified by
* `indices`.
*
* `indices` is an K-dimensional integer tensor, best thought of as a
* (K-1)-dimensional tensor of indices into input, where each element defines a
* slice of input:
* output[\\(i_0, ..., i_{K-2}\\)] = input[indices[\\(i_0, ..., i_{K-2}\\)]]
*
* Whereas in `tf.gather`, `indices` defines slices into the first dimension of
* input, in `tf.gatherND`, `indices` defines slices into the first N dimensions
* of input, where N = indices.shape[-1].
*
* The last dimension of indices can be at most the rank of input:
* indices.shape[-1] <= input.rank
*
* The last dimension of `indices` corresponds to elements
* (if indices.shape[-1] == input.rank) or slices
* (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of
* input.
* The output tensor has shape
* indices.shape[:-1] + input.shape[indices.shape[-1]:]
*
* Note that on CPU, if an out of bound index is found, an error is returned. On
* GPU, if an out of bound index is found, a 0 is stored in the corresponding
* output value.
*
* ```js
* const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');
* const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);
* tf.gatherND(input, indices).print() // [10, 11]
* ```
*
* @param x The tensor from which to gather values.
* @param indices Index tensor, must be of type int32.
*
* @doc {heading: 'Operations', subheading: 'Slicing and Joining'}
*/
function gatherND_(x, indices) {
const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');
const $x = convertToTensor(x, 'x', 'gatherND', 'string_or_numeric');
const inputs = { params: $x, indices: $indices };
return ENGINE.runKernel(GatherNd, inputs);
}
const gatherND = op({ gatherND_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Normalize noise shape based on provided tensor and noise shape.
*
* @param x Tensor.
* @param noiseShape The shape for the randomly generated keep/drop flags, as
* an array of numbers. Optional.
* @returns Normalized noise shape.
*/
function getNoiseShape(x, noiseShape) {
if (noiseShape == null) {
return x.shape.slice();
}
if (arraysEqual(x.shape, noiseShape)) {
return noiseShape;
}
if (x.shape.length === noiseShape.length) {
const newDimension = [];
for (let i = 0; i < x.shape.length; i++) {
if (noiseShape[i] == null && x.shape[i] != null) {
newDimension.push(x.shape[i]);
}
else {
newDimension.push(noiseShape[i]);
}
}
return newDimension;
}
return noiseShape;
}
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Computes dropout.
*
* ```js
* const x = tf.tensor1d([1, 2, 2, 1]);
* const rate = 0.75;
* const output = tf.dropout(x, rate);
* output.print();
* ```
*
* @param x A floating point Tensor or TensorLike.
* @param rate A float in the range [0, 1). The probability that each element
* of x is discarded.
* @param noiseShape An array of numbers of type int32, representing the
* shape for randomly generated keep/drop flags. If the noiseShape has null
* value, it will be automatically replaced with the x's relative dimension
* size. Optional.
* @param seed Used to create random seeds. Optional.
* @returns A Tensor of the same shape of x.
*
* @doc {heading: 'Operations', subheading: 'Dropout'}
*/
function dropout_(x, rate, noiseShape, seed) {
const $x = convertToTensor(x, 'x', 'dropout');
assert($x.dtype === 'float32', () => `x has to be a floating point tensor since it's going to be ` +
`scaled, but got a ${$x.dtype} tensor instead.`);
assert(rate >= 0 && rate < 1, () => `rate must be a float in the range [0, 1), but got ${rate}.`);
if (rate === 0) {
return x instanceof Tensor ? $x.clone() : $x;
}
const $noiseShape = getNoiseShape($x, noiseShape);
const keepProb = 1 - rate;
const multiplier = div(floor(add$1(randomUniform($noiseShape, 0, 1, 'float32', seed), keepProb)), keepProb);
return mul($x, multiplier);
}
const dropout = op({ dropout_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
function enclosingPowerOfTwo(value) {
// Return 2**N for integer N such that 2**N >= value.
return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2.0))));
}
function cosineWindow(windowLength, a, b) {
const even = 1 - windowLength % 2;
const newValues = new Float32Array(windowLength);
for (let i = 0; i < windowLength; ++i) {
const cosArg = (2.0 * Math.PI * i) / (windowLength + even - 1);
newValues[i] = a - b * Math.cos(cosArg);
}
return tensor1d(newValues, 'float32');
}
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Returns whether the targets are in the top K predictions.
*
* ```js
* const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);
* const targets = tf.tensor1d([2, 0]);
* const precision = await tf.inTopKAsync(predictions, targets);
* precision.print();
* ```
* @param predictions 2-D or higher `tf.Tensor` with last dimension being
* at least `k`.
* @param targets 1-D or higher `tf.Tensor`.
* @param k Optional Number of top elements to look at for computing precision,
* default to 1.
*
* @doc {heading: 'Operations', subheading: 'Evaluation'}
*/
async function inTopKAsync_(predictions, targets, k = 1) {
const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');
const $targets = convertToTensor(targets, 'targets', 'inTopK');
assert($predictions.rank > 1, () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +
`but got ${$predictions.rank}`);
assert($predictions.rank - 1 === $targets.rank, () => `predictions rank should be 1 larger than ` +
`targets rank, but got predictions rank ` +
`${$predictions.rank} and targets rank ${$targets.rank}`);
assertShapesMatch($predictions.shape.slice(0, $predictions.shape.length - 1), $targets.shape, `predictions's shape should be align with the targets' shape, ` +
'except the last dimension.');
const lastDim = $predictions.shape[$predictions.shape.length - 1];
assert(k > 0 && k <= lastDim, () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +
`dimension (${lastDim}), but got ${k}`);
const predictionsVals = await $predictions.data();
const targetsVals = await $targets.data();
// Reshape predictionsVals into a 2d tensor [batch, lastDim]
// and look up topK along lastDim.
const [batch, size] = [predictionsVals.length / lastDim, lastDim];
const precision = getTypedArrayFromDType('bool', batch);
for (let b = 0; b < batch; b++) {
const offset = b * size;
const vals = predictionsVals.subarray(offset, offset + size);
const valAndInd = [];
for (let i = 0; i < vals.length; i++) {
valAndInd.push({ value: vals[i], index: i });
}
valAndInd.sort((a, b) => b.value - a.value);
precision[b] = 0;
for (let i = 0; i < k; i++) {
if (valAndInd[i].index === targetsVals[b]) {
precision[b] = 1;
break;
}
}
}
if (predictions !== $predictions) {
$predictions.dispose();
}
if (targets !== $targets) {
$targets.dispose();
}
// Output precision has the same shape as targets.
return tensor(precision, $targets.shape, 'bool');
}
const inTopKAsync = inTopKAsync_;
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
// Returns gradient for fused activation.
function getFusedDyActivation(dy, y, activation) {
if (activation == null || activation === 'linear') {
return dy;
}
if (activation === 'relu') {
return mul(dy, step(y));
}
throw new Error(`Cannot compute gradient for fused activation ${activation}.`);
}
// Returns gradient for fused bias.
function getFusedBiasGradient(bias, dyActivation) {
let res = dyActivation;
const reduceAxes = getReductionAxes(bias.shape, dyActivation.shape);
if (reduceAxes.length > 0) {
res = sum$1(res, reduceAxes);
}
return reshape(res, bias.shape);
}
function applyActivation(x, activation, preluActivationWeights, leakyreluAlpha) {
if (activation === 'linear') {
return x;
}
else if (activation === 'relu') {
return relu(x);
}
else if (activation === 'elu') {
return elu(x);
}
else if (activation === 'relu6') {
return relu6(x);
}
else if (activation === 'prelu') {
return prelu(x, preluActivationWeights);
}
else if (activation === 'leakyrelu') {
return leakyRelu(x, leakyreluAlpha);
}
else if (activation === 'sigmoid') {
return sigmoid(x);
}
throw new Error(`Unknown fused activation ${activation}.`);
}
// Whether we should call fused ops.
const shouldFuse = (gradientDepth, activation) => {
const gradientMode = gradientDepth > 0;
return !gradientMode || activation === 'linear';
};
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Computes a 2D convolution over the input x, optionally fused with adding a
* bias and applying an activation.
*
* ```js
* const inputDepth = 2;
* const inShape = [2, 2, 2, inputDepth];
* const outputDepth = 2;
* const fSize = 1;
* const pad = 0;
* const strides = 1;
*
* const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
* 16], inShape);
* const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,
* outputDepth]);
*
* tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',
* dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();
* ```
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter, rank 4, of shape
* `[filterHeight, filterWidth, inDepth, outDepth]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid` output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dataFormat An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`) to be
* applied
* after biasAdd.
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
* activation.
*/
function fusedConv2d_({ x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha }) {
activation = activation || 'linear';
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = conv2d(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
const $x = convertToTensor(x, 'x', 'conv2d');
const $filter = convertToTensor(filter, 'filter', 'conv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ` +
`${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ` +
`${$filter.rank}.`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in fused conv2d: pad must be an integer when using, ` +
`dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
assert(x4D.shape[3] === $filter.shape[2], () => `Error in conv2d: depth of input (${x4D.shape[3]}) must match ` +
`input depth for filter ${$filter.shape[2]}.`);
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in conv2D: Either strides or dilations must be 1. ' +
`Got strides ${strides} and dilations '${dilations}'`);
assert(dataFormat === 'NHWC', () => `Error in conv2d: got dataFormat of ${dataFormat} but only NHWC is currently supported.`);
const convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused conv2d');
[$bias] = makeTypesMatch($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused conv2d');
}
const grad = (dy, saved) => {
const [$filter, x4D, y, $bias] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of fused conv2D: ' +
`dilation rates greater than 1 ` +
`are not yet supported in gradients. Got dilations '${dilations}'`);
const xDer = conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);
const filterDer = conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);
const der = [xDer, filterDer];
if ($bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
der.push(biasDer);
}
return der;
};
const inputs = {
x: x4D,
filter: $filter,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = {
strides,
pad,
dataFormat,
dilations,
dimRoundingMode,
activation,
leakyreluAlpha
};
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((x4D, filter, save) => {
let res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(FusedConv2D, inputs, attrs);
save([filter, x4D, res]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOp(x4D, $filter);
}
else {
const customOpWithBias = customGrad((x4D, filter, bias, save) => {
let res = ENGINE.runKernel(FusedConv2D, inputs, attrs);
save([filter, x4D, res, bias]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOpWithBias(x4D, $filter, $bias);
}
}
const conv2d$1 = op({ fusedConv2d_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Computes depthwise 2D convolution, optionally fused with adding a
* bias and applying an activation.
*
* Given a 4D `input` array and a `filter` array of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing
* `inChannels` convolutional filters of depth 1, this op applies a
* different filter to each input channel (expanding from 1 channel to
* `channelMultiplier` channels for each), then concatenates the results
* together. The output has `inChannels * channelMultiplier` channels.
*
* See
* [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](
* https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)
* for more details.
*
* @param obj An object with the following properties:
* @param x The input tensor, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is
* assumed.
* @param filter The filter tensor, rank 4, of shape
* `[filterHeight, filterWidth, inChannels, channelMultiplier]`.
* @param strides The strides of the convolution: `[strideHeight,
* strideWidth]`. If strides is a single number, then `strideHeight ==
* strideWidth`.
* @param pad The type of padding algorithm.
* - `same` and stride 1: output will be of same size as input,
* regardless of filter size.
* - `valid`: output will be smaller than input if filter is larger
* than 1x1.
* - For more info, see this guide:
* [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](
* https://www.tensorflow.org/api_docs/python/tf/nn/convolution)
* @param dilations The dilation rates: `[dilationHeight, dilationWidth]`
* in which we sample input values across the height and width dimensions
* in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single
* number, then `dilationHeight == dilationWidth`. If it is greater than
* 1, then all values of `strides` must be 1.
* @param dataFormat: An optional string from: "NHWC", "NCHW". Defaults to
* "NHWC". Specify the data format of the input and output data. With the
* default format "NHWC", the data is stored in the order of: [batch,
* height, width, channels]. Only "NHWC" is currently supported.
* @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is
* provided, it will default to truncate.
* @param bias Tensor to be added to the result.
* @param activation Name of activation kernel (defaults to `linear`).
* @param preluActivationWeights Tensor of prelu weights to be applied as part
* of a `prelu` activation, typically the same shape as `x`.
* @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`
* activation.
*/
function fusedDepthwiseConv2d_({ x, filter, strides, pad, dataFormat = 'NHWC', dilations = [1, 1], dimRoundingMode, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha }) {
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = depthwiseConv2d(x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
const $x = convertToTensor(x, 'x', 'depthwiseConv2d');
const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');
let x4D = $x;
let reshapedTo4D = false;
if ($x.rank === 3) {
reshapedTo4D = true;
x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);
}
assert(x4D.rank === 4, () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +
`rank ${x4D.rank}.`);
assert($filter.rank === 4, () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +
`but got rank ${$filter.rank}.`);
assert(x4D.shape[3] === $filter.shape[2], () => `Error in fused depthwiseConv2d: number of input channels ` +
`(${x4D.shape[3]}) must match the inChannels dimension in ` +
`filter ${$filter.shape[2]}.`);
if (dilations == null) {
dilations = [1, 1];
}
assert(eitherStridesOrDilationsAreOne(strides, dilations), () => 'Error in fused depthwiseConv2d: Either strides or dilations must ' +
`be 1. Got strides ${strides} and dilations '${dilations}'`);
if (dimRoundingMode != null) {
assert(isInt(pad), () => `Error in fused depthwiseConv2d: pad must be an integer when ` +
`using dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);
}
const convInfo = computeConv2DInfo(x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode, true /* depthwise */);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused conv2d');
[$bias] = makeTypesMatch($bias, $x);
assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');
}
const grad = (dy, saved) => {
assert(tupleValuesAreOne(dilations), () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +
`greater than 1 are not yet supported. Got dilations ` +
`'${dilations}'`);
const [$filter, x4D, y, bias] = saved;
const dyActivation = getFusedDyActivation(dy, y, activation);
const xDer = depthwiseConv2dNativeBackpropInput(x4D.shape, dyActivation, $filter, strides, pad, dilations, dimRoundingMode);
const filterDer = depthwiseConv2dNativeBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad, dilations, dimRoundingMode);
if (bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
return [xDer, filterDer, biasDer];
}
return [xDer, filterDer];
};
const inputs = {
x: x4D,
filter: $filter,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = {
strides,
pad,
dataFormat,
dilations,
dimRoundingMode,
activation,
leakyreluAlpha
};
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((x4D, filter, save) => {
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
save([filter, x4D, res]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOp(x4D, $filter);
}
else {
const customOpWithBias = customGrad((x4D, filter, bias, save) => {
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(FusedDepthwiseConv2D, inputs, attrs);
save([filter, x4D, res, bias]);
if (reshapedTo4D) {
// tslint:disable-next-line: no-unnecessary-type-assertion
res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return { value: res, gradFunc: grad };
});
return customOpWithBias(x4D, $filter, $bias);
}
}
const depthwiseConv2d$1 = op({ fusedDepthwiseConv2d_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the dot product of two matrices with optional activation and bias.
*
* ```js
* const a = tf.tensor2d([-1, -2], [1, 2]);
* const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
* const bias = tf.tensor2d([1, 2], [1, 2]);
*
* tf.fused.matMul({a, b, bias, activation: 'relu'}).print();
* ```
*
* @param obj An object with the following properties:
* - `a` First matrix in dot product operation.
* - `b` Second matrix in dot product operation.
* - `transposeA` If true, `a` is transposed before multiplication.
* - `transposeB` If true, `b` is transposed before multiplication.
* - `bias` Matrix to be added to the result.
* - `activation` Name of activation kernel (defaults to `linear`).
* - `preluActivationWeights` Tensor of prelu weights.
* - `leakyreluAlpha` Alpha of leakyrelu.
*/
function fusedMatMul_({ a, b, transposeA = false, transposeB = false, bias, activation = 'linear', preluActivationWeights, leakyreluAlpha, }) {
if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {
let result = matMul(a, b, transposeA, transposeB);
if (bias != null) {
result = add$1(result, bias);
}
return applyActivation(result, activation, preluActivationWeights, leakyreluAlpha);
}
let $a = convertToTensor(a, 'a', 'fused matMul');
let $b = convertToTensor(b, 'b', 'fused matMul');
[$a, $b] = makeTypesMatch($a, $b);
const innerShapeA = transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];
const innerShapeB = transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];
const outerShapeA = transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];
const outerShapeB = transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];
const outerDimsA = $a.shape.slice(0, -2);
const outerDimsB = $b.shape.slice(0, -2);
const batchDimA = sizeFromShape(outerDimsA);
const batchDimB = sizeFromShape(outerDimsB);
assert($a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank, () => `Error in fused matMul: inputs must have the same rank of at ` +
`least 2, got ranks ${$a.rank} and ${$b.rank}.`);
assert(arraysEqual(outerDimsA, outerDimsB), () => `Error in fused matMul: outer dimensions (${outerDimsA}) and (` +
`${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} must match.`);
assert(innerShapeA === innerShapeB, () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +
`${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +
`${$b.shape} and transposeA=${transposeA}` +
` and transposeB=${transposeB} must match.`);
const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);
const a3D = transposeA ?
reshape($a, [batchDimA, innerShapeA, outerShapeA]) :
reshape($a, [batchDimA, outerShapeA, innerShapeA]);
const b3D = transposeB ?
reshape($b, [batchDimB, outerShapeB, innerShapeB]) :
reshape($b, [batchDimB, innerShapeB, outerShapeB]);
let $bias;
if (bias != null) {
$bias = convertToTensor(bias, 'bias', 'fused matMul');
[$bias] = makeTypesMatch($bias, $a);
assertAndGetBroadcastShape(outShape, $bias.shape);
}
let $preluActivationWeights;
if (preluActivationWeights != null) {
$preluActivationWeights = convertToTensor(preluActivationWeights, 'prelu weights', 'fused matMul');
}
const grad = (dy, saved) => {
const [a3D, b3D, y, $bias] = saved;
// we reshape dy because the result of the forward is not
// necessarily going to be a 3d tensor due to a reshape done at the end of
// the customOp.
const dyActivation = getFusedDyActivation(reshape(dy, y.shape), y, activation);
let aDer;
let bDer;
if (!transposeA && !transposeB) {
aDer = matMul(dyActivation, b3D, false, true);
bDer = matMul(a3D, dyActivation, true, false);
}
else if (!transposeA && transposeB) {
aDer = matMul(dyActivation, b3D, false, false);
bDer = matMul(dyActivation, a3D, true, false);
}
else if (transposeA && !transposeB) {
aDer = matMul(b3D, dyActivation, false, true);
bDer = matMul(a3D, dyActivation, false, false);
}
else {
aDer = matMul(b3D, dyActivation, true, true);
bDer = matMul(dyActivation, a3D, true, true);
}
if (bias != null) {
const biasDer = getFusedBiasGradient($bias, dyActivation);
return [aDer, bDer, biasDer];
}
else {
return [aDer, bDer];
}
};
const inputs = {
a: a3D,
b: b3D,
bias: $bias,
preluActivationWeights: $preluActivationWeights
};
const attrs = { transposeA, transposeB, activation, leakyreluAlpha };
// Depending on the the params passed in we will have different number of
// inputs and thus a a different number of elements in the gradient.
if (bias == null) {
const customOp = customGrad((a3D, b3D, save) => {
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(_FusedMatMul, inputs, attrs);
save([a3D, b3D, res]);
return { value: reshape(res, outShape), gradFunc: grad };
});
return customOp(a3D, b3D);
}
else {
const customOpWithBias = customGrad((a3D, b3D, $bias, save) => {
const res =
// tslint:disable-next-line: no-unnecessary-type-assertion
ENGINE.runKernel(_FusedMatMul, inputs, attrs);
save([a3D, b3D, res, $bias]);
return { value: reshape(res, outShape), gradFunc: grad };
});
return customOpWithBias(a3D, b3D, $bias);
}
}
const matMul$1 = op({ fusedMatMul_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Generate a hamming window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hammingWindow(10).print();
* ```
* @param The length of window
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hammingWindow_(windowLength) {
return cosineWindow(windowLength, 0.54, 0.46);
}
const hammingWindow = op({ hammingWindow_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Generate a Hann window.
*
* See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows
*
* ```js
* tf.signal.hannWindow(10).print();
* ```
* @param The length of window
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function hannWindow_(windowLength) {
return cosineWindow(windowLength, 0.5, 0.5);
}
const hannWindow = op({ hannWindow_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Expands input into frames of frameLength.
* Slides a window size with frameStep.
*
* ```js
* tf.signal.frame([1, 2, 3], 2, 1).print();
* ```
* @param signal The input tensor to be expanded
* @param frameLength Length of each frame
* @param frameStep The frame hop size in samples.
* @param padEnd Whether to pad the end of signal with padValue.
* @param padValue An number to use where the input signal does
* not exist when padEnd is True.
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function frame_(signal, frameLength, frameStep, padEnd = false, padValue = 0) {
let start = 0;
const output = [];
while (start + frameLength <= signal.size) {
output.push(slice(signal, start, frameLength));
start += frameStep;
}
if (padEnd) {
while (start < signal.size) {
const padLen = (start + frameLength) - signal.size;
const pad = concat([
slice(signal, start, frameLength - padLen), fill([padLen], padValue)
]);
output.push(pad);
start += frameStep;
}
}
if (output.length === 0) {
return tensor2d([], [0, frameLength]);
}
return reshape(concat(output), [output.length, frameLength]);
}
const frame = op({ frame_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the Short-time Fourier Transform of signals
* See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform
*
* ```js
* const input = tf.tensor1d([1, 1, 1, 1, 1])
* tf.signal.stft(input, 3, 1).print();
* ```
* @param signal 1-dimensional real value tensor.
* @param frameLength The window length of samples.
* @param frameStep The number of samples to step.
* @param fftLength The size of the FFT to apply.
* @param windowFn A callable that takes a window length and returns 1-d tensor.
*
* @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}
*/
function stft_(signal, frameLength, frameStep, fftLength, windowFn = hannWindow) {
if (fftLength == null) {
fftLength = enclosingPowerOfTwo(frameLength);
}
const framedSignal = frame(signal, frameLength, frameStep);
const windowedSignal = mul(framedSignal, windowFn(frameLength));
return rfft(windowedSignal, fftLength);
}
const stft = op({ stft_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Extracts crops from the input image tensor and resizes them using bilinear
* sampling or nearest neighbor sampling (possibly with aspect ratio change)
* to a common output size specified by cropSize.
*
* @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,
* where imageHeight and imageWidth must be positive, specifying the
* batch of images from which to take crops
* @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized
* coordinates of the box in the boxInd[i]'th image in the batch
* @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range
* `[0, batch)` that specifies the image that the `i`-th box refers to.
* @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`
* specifying the size to which all crops are resized to.
* @param method Optional string from `'bilinear' | 'nearest'`,
* defaults to bilinear, which specifies the sampling method for resizing
* @param extrapolationValue A threshold for deciding when to remove boxes based
* on score. Defaults to 0.
* @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function cropAndResize_(image, boxes, boxInd, cropSize, method = 'bilinear', extrapolationValue = 0) {
const $image = convertToTensor(image, 'image', 'cropAndResize');
const $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');
const $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');
const numBoxes = $boxes.shape[0];
assert($image.rank === 4, () => 'Error in cropAndResize: image must be rank 4,' +
`but got rank ${$image.rank}.`);
assert($boxes.rank === 2 && $boxes.shape[1] === 4, () => `Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +
`but had shape ${$boxes.shape}.`);
assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, () => `Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +
`but had shape ${$boxes.shape}.`);
assert(cropSize.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got ` +
`length ${cropSize.length}.`);
assert(cropSize[0] >= 1 && cropSize[1] >= 1, () => `cropSize must be atleast [1,1], but was ${cropSize}`);
assert(method === 'bilinear' || method === 'nearest', () => `method must be bilinear or nearest, but was ${method}`);
const inputs = { image: $image, boxes: $boxes, boxInd: $boxInd };
const attrs = { method, extrapolationValue, cropSize };
const res = ENGINE.runKernel(CropAndResize, inputs, attrs);
return res;
}
const cropAndResize = op({ cropAndResize_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Flips the image left to right. Currently available in the CPU, WebGL, and
* WASM backends.
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
*/
/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */
function flipLeftRight_(image) {
const $image = convertToTensor(image, 'image', 'flipLeftRight', 'float32');
assert($image.rank === 4, () => 'Error in flipLeftRight: image must be rank 4,' +
`but got rank ${$image.rank}.`);
const inputs = { image: $image };
const res = ENGINE.runKernel(FlipLeftRight, inputs, {});
return res;
}
const flipLeftRight = op({ flipLeftRight_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Converts images from grayscale to RGB format.
*
* @param image A grayscale tensor to convert. The `image`'s last dimension must
* be size 1 with at least a two-dimensional shape.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function grayscaleToRGB_(image) {
const $image = convertToTensor(image, 'image', 'grayscaleToRGB');
const lastDimsIdx = $image.rank - 1;
const lastDims = $image.shape[lastDimsIdx];
assert($image.rank >= 2, () => 'Error in grayscaleToRGB: images must be at least rank 2, ' +
`but got rank ${$image.rank}.`);
assert(lastDims === 1, () => 'Error in grayscaleToRGB: last dimension of a grayscale image ' +
`should be size 1, but got size ${lastDims}.`);
const reps = new Array($image.rank);
reps.fill(1, 0, lastDimsIdx);
reps[lastDimsIdx] = 3;
return tile($image, reps);
}
const grayscaleToRGB = op({ grayscaleToRGB_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Rotates the input image tensor counter-clockwise with an optional offset
* center of rotation. Currently available in the CPU, WebGL, and WASM backends.
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
* @param radians The amount of rotation.
* @param fillValue The value to fill in the empty space leftover
* after rotation. Can be either a single grayscale value (0-255), or an
* array of three numbers `[red, green, blue]` specifying the red, green,
* and blue channels. Defaults to `0` (black).
* @param center The center of rotation. Can be either a single value (0-1), or
* an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates
* the image around its center).
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function rotateWithOffset_(image, radians, fillValue = 0, center = 0.5) {
const $image = convertToTensor(image, 'image', 'rotateWithOffset', 'float32');
assert($image.rank === 4, () => 'Error in rotateWithOffset: image must be rank 4,' +
`but got rank ${$image.rank}.`);
const inputs = { image: $image };
const attrs = { radians, fillValue, center };
const res = ENGINE.runKernel(RotateWithOffset, inputs, attrs);
return res;
}
const rotateWithOffset = op({ rotateWithOffset_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
if (iouThreshold == null) {
iouThreshold = 0.5;
}
if (scoreThreshold == null) {
scoreThreshold = Number.NEGATIVE_INFINITY;
}
if (softNmsSigma == null) {
softNmsSigma = 0.0;
}
const numBoxes = boxes.shape[0];
maxOutputSize = Math.min(maxOutputSize, numBoxes);
assert(0 <= iouThreshold && iouThreshold <= 1, () => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`);
assert(boxes.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`);
assert(boxes.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`);
assert(scores.rank === 1, () => 'scores must be a 1D tensor');
assert(scores.shape[0] === numBoxes, () => `scores has incompatible shape with boxes. Expected ${numBoxes}, ` +
`but was ${scores.shape[0]}`);
assert(0 <= softNmsSigma && softNmsSigma <= 1, () => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`);
return { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const attrs = { maxOutputSize, iouThreshold, scoreThreshold };
return ENGINE.runKernel(NonMaxSuppressionV3, { boxes: $boxes, scores: $scores }, attrs);
}
const nonMaxSuppression = op({ nonMaxSuppression_ });
/**
* @license
* Copyright 2019 Google LLC. 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.
* =============================================================================
*/
/**
* Inserts a value into a sorted array. This method allows duplicate, meaning it
* allows inserting duplicate value, in which case, the element will be inserted
* at the lowest index of the value.
* @param arr The array to modify.
* @param element The element to insert.
* @param comparator Optional. If no comparator is specified, elements are
* compared using array_util.defaultComparator, which is suitable for Strings
* and Numbers in ascending arrays. If the array contains multiple instances of
* the target value, the left-most instance will be returned. To provide a
* comparator, it should take 2 arguments to compare and return a negative,
* zero, or a positive number.
*/
function binaryInsert(arr, element, comparator) {
const index = binarySearch(arr, element, comparator);
const insertionPoint = index < 0 ? -(index + 1) : index;
arr.splice(insertionPoint, 0, element);
}
/**
* Searches the array for the target using binary search, returns the index
* of the found element, or position to insert if element not found. If no
* comparator is specified, elements are compared using array_
* util.defaultComparator, which is suitable for Strings and Numbers in
* ascending arrays. If the array contains multiple instances of the target
* value, the left-most instance will be returned.
* @param arr The array to be searched in.
* @param target The target to be searched for.
* @param comparator Should take 2 arguments to compare and return a negative,
* zero, or a positive number.
* @return Lowest index of the target value if found, otherwise the insertion
* point where the target should be inserted, in the form of
* (-insertionPoint - 1).
*/
function binarySearch(arr, target, comparator) {
return binarySearch_(arr, target, comparator || defaultComparator);
}
/**
* Compares its two arguments for order.
* @param a The first element to be compared.
* @param b The second element to be compared.
* @return A negative number, zero, or a positive number as the first
* argument is less than, equal to, or greater than the second.
*/
function defaultComparator(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
function binarySearch_(arr, target, comparator) {
let left = 0;
let right = arr.length;
let middle = 0;
let found = false;
while (left < right) {
middle = left + ((right - left) >>> 1);
const compareResult = comparator(target, arr[middle]);
if (compareResult > 0) {
left = middle + 1;
}
else {
right = middle;
// If compareResult is 0, the value is found. We record it is found,
// and then keep looking because there may be duplicate.
found = !compareResult;
}
}
return found ? left : -left - 1;
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function nonMaxSuppressionV3Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */);
}
function nonMaxSuppressionV4Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, 0 /* softNmsSigma */, false /* returnScoresTensor */, padToMaxOutputSize /* padToMaxOutputSize */, true
/* returnValidOutputs */ );
}
function nonMaxSuppressionV5Impl(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) {
return nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, true /* returnScoresTensor */);
}
function nonMaxSuppressionImpl_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma, returnScoresTensor = false, padToMaxOutputSize = false, returnValidOutputs = false) {
// The list is sorted in ascending order, so that we can always pop the
// candidate with the largest score in O(1) time.
const candidates = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] > scoreThreshold) {
candidates.push({ score: scores[i], boxIndex: i, suppressBeginIndex: 0 });
}
}
candidates.sort(ascendingComparator);
// If softNmsSigma is 0, the outcome of this algorithm is exactly same as
// before.
const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;
const selectedIndices = [];
const selectedScores = [];
while (selectedIndices.length < maxOutputSize && candidates.length > 0) {
const candidate = candidates.pop();
const { score: originalScore, boxIndex, suppressBeginIndex } = candidate;
if (originalScore < scoreThreshold) {
break;
}
// Overlapping boxes are likely to have similar scores, therefore we
// iterate through the previously selected boxes backwards in order to
// see if candidate's score should be suppressed. We use
// suppressBeginIndex to track and ensure a candidate can be suppressed
// by a selected box no more than once. Also, if the overlap exceeds
// iouThreshold, we simply ignore the candidate.
let ignoreCandidate = false;
for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {
const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);
if (iou >= iouThreshold) {
ignoreCandidate = true;
break;
}
candidate.score =
candidate.score * suppressWeight(iouThreshold, scale, iou);
if (candidate.score <= scoreThreshold) {
break;
}
}
// At this point, if `candidate.score` has not dropped below
// `scoreThreshold`, then we know that we went through all of the
// previous selections and can safely update `suppressBeginIndex` to the
// end of the selected array. Then we can re-insert the candidate with
// the updated score and suppressBeginIndex back in the candidate list.
// If on the other hand, `candidate.score` has dropped below the score
// threshold, we will not add it back to the candidates list.
candidate.suppressBeginIndex = selectedIndices.length;
if (!ignoreCandidate) {
// Candidate has passed all the tests, and is not suppressed, so
// select the candidate.
if (candidate.score === originalScore) {
selectedIndices.push(boxIndex);
selectedScores.push(candidate.score);
}
else if (candidate.score > scoreThreshold) {
// Candidate's score is suppressed but is still high enough to be
// considered, so add back to the candidates list.
binaryInsert(candidates, candidate, ascendingComparator);
}
}
}
// NonMaxSuppressionV4 feature: padding output to maxOutputSize.
const validOutputs = selectedIndices.length;
const elemsToPad = maxOutputSize - validOutputs;
if (padToMaxOutputSize && elemsToPad > 0) {
selectedIndices.push(...new Array(elemsToPad).fill(0));
selectedScores.push(...new Array(elemsToPad).fill(0.0));
}
const result = { selectedIndices };
if (returnScoresTensor) {
result['selectedScores'] = selectedScores;
}
if (returnValidOutputs) {
result['validOutputs'] = validOutputs;
}
return result;
}
function intersectionOverUnion(boxes, i, j) {
const iCoord = boxes.subarray(i * 4, i * 4 + 4);
const jCoord = boxes.subarray(j * 4, j * 4 + 4);
const yminI = Math.min(iCoord[0], iCoord[2]);
const xminI = Math.min(iCoord[1], iCoord[3]);
const ymaxI = Math.max(iCoord[0], iCoord[2]);
const xmaxI = Math.max(iCoord[1], iCoord[3]);
const yminJ = Math.min(jCoord[0], jCoord[2]);
const xminJ = Math.min(jCoord[1], jCoord[3]);
const ymaxJ = Math.max(jCoord[0], jCoord[2]);
const xmaxJ = Math.max(jCoord[1], jCoord[3]);
const areaI = (ymaxI - yminI) * (xmaxI - xminI);
const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
if (areaI <= 0 || areaJ <= 0) {
return 0.0;
}
const intersectionYmin = Math.max(yminI, yminJ);
const intersectionXmin = Math.max(xminI, xminJ);
const intersectionYmax = Math.min(ymaxI, ymaxJ);
const intersectionXmax = Math.min(xmaxI, xmaxJ);
const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *
Math.max(intersectionXmax - intersectionXmin, 0.0);
return intersectionArea / (areaI + areaJ - intersectionArea);
}
// A Gaussian penalty function, this method always returns values in [0, 1].
// The weight is a function of similarity, the more overlap two boxes are, the
// smaller the weight is, meaning highly overlapping boxe will be significantly
// penalized. On the other hand, a non-overlapping box will not be penalized.
function suppressWeight(iouThreshold, scale, iou) {
const weight = Math.exp(scale * iou * iou);
return iou <= iouThreshold ? weight : 0.0;
}
function ascendingComparator(c1, c2) {
// For objects with same scores, we make the object with the larger index go
// first. In an array that pops from the end, this means that the object with
// the smaller index will be popped first. This ensures the same output as
// the TensorFlow python version.
return (c1.score - c2.score) ||
((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This is the async version of `nonMaxSuppression`
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @return A 1D tensor with the selected box indices.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);
maxOutputSize = inputs.maxOutputSize;
iouThreshold = inputs.iouThreshold;
scoreThreshold = inputs.scoreThreshold;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices } = nonMaxSuppressionV3Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return tensor1d(selectedIndices, 'int32');
}
const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, softNmsSigma = 0.0) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = params.maxOutputSize;
iouThreshold = params.iouThreshold;
scoreThreshold = params.scoreThreshold;
softNmsSigma = params.softNmsSigma;
const inputs = { boxes: $boxes, scores: $scores };
const attrs = { maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma };
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(NonMaxSuppressionV5, inputs, attrs);
return { selectedIndices: result[0], selectedScores: result[1] };
}
const nonMaxSuppressionWithScore = op({ nonMaxSuppressionWithScore_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union).
*
* This op also supports a Soft-NMS mode (c.f.
* Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score
* of other overlapping boxes, therefore favoring different regions of the image
* with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`
* parameter to be larger than 0.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param softNmsSigma A float representing the sigma parameter for Soft NMS.
* When sigma is 0, it falls back to nonMaxSuppression.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - selectedScores: A 1D tensor with the corresponding scores for each
* selected box.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, softNmsSigma = 0.0) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
maxOutputSize = params.maxOutputSize;
iouThreshold = params.iouThreshold;
scoreThreshold = params.scoreThreshold;
softNmsSigma = params.softNmsSigma;
const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);
const boxesVals = boxesAndScores[0];
const scoresVals = boxesAndScores[1];
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices, selectedScores } = nonMaxSuppressionV5Impl(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return {
selectedIndices: tensor1d(selectedIndices, 'int32'),
selectedScores: tensor1d(selectedScores)
};
}
const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union), with an option to pad results.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param padToMaxOutputSize Defalts to false. If true, size of output
* `selectedIndices` is padded to maxOutputSize.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
* are valid. Valid elements occur first, then padding.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function nonMaxSuppressionPadded_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null /* softNmsSigma */);
const $maxOutputSize = params.maxOutputSize;
const $iouThreshold = params.iouThreshold;
const $scoreThreshold = params.scoreThreshold;
const inputs = { boxes: $boxes, scores: $scores };
const attrs = {
maxOutputSize: $maxOutputSize,
iouThreshold: $iouThreshold,
scoreThreshold: $scoreThreshold,
padToMaxOutputSize
};
// tslint:disable-next-line: no-unnecessary-type-assertion
const result = ENGINE.runKernel(NonMaxSuppressionV4, inputs, attrs);
return { selectedIndices: result[0], validOutputs: result[1] };
}
const nonMaxSuppressionPadded = op({ nonMaxSuppressionPadded_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Asynchronously performs non maximum suppression of bounding boxes based on
* iou (intersection over union), with an option to pad results.
*
* @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is
* `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of
* the bounding box.
* @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.
* @param maxOutputSize The maximum number of boxes to be selected.
* @param iouThreshold A float representing the threshold for deciding whether
* boxes overlap too much with respect to IOU. Must be between [0, 1].
* Defaults to 0.5 (50% box overlap).
* @param scoreThreshold A threshold for deciding when to remove boxes based
* on score. Defaults to -inf, which means any score is accepted.
* @param padToMaxOutputSize Defalts to false. If true, size of output
* `selectedIndices` is padded to maxOutputSize.
* @return A map with the following properties:
* - selectedIndices: A 1D tensor with the selected box indices.
* - validOutputs: A scalar denoting how many elements in `selectedIndices`
* are valid. Valid elements occur first, then padding.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
async function nonMaxSuppressionPaddedAsync_(boxes, scores, maxOutputSize, iouThreshold = 0.5, scoreThreshold = Number.NEGATIVE_INFINITY, padToMaxOutputSize = false) {
const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');
const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');
const params = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, null /* softNmsSigma */);
const $maxOutputSize = params.maxOutputSize;
const $iouThreshold = params.iouThreshold;
const $scoreThreshold = params.scoreThreshold;
const [boxesVals, scoresVals] = await Promise.all([$boxes.data(), $scores.data()]);
// We call a cpu based impl directly with the typedarray data here rather
// than a kernel because all kernels are synchronous (and thus cannot await
// .data()).
const { selectedIndices, validOutputs } = nonMaxSuppressionV4Impl(boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold, padToMaxOutputSize);
if ($boxes !== boxes) {
$boxes.dispose();
}
if ($scores !== scores) {
$scores.dispose();
}
return {
selectedIndices: tensor1d(selectedIndices, 'int32'),
validOutputs: scalar(validOutputs, 'int32')
};
}
const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Bilinear resize a single 3D image or a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to `false`. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers
* are at 0.5, which would make the floating point coordinates of the top
* left pixel 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeBilinear_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = convertToTensor(images, 'images', 'resizeBilinear');
assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
assert(size.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ` +
`${size}.`);
assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeBilinear: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(ResizeBilinear, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeBilinear = op({ resizeBilinear_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* NearestNeighbor resize a batch of 3D images to a new shape.
*
* @param images The images, of rank 4 or rank 3, of shape
* `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.
* @param size The new shape `[newHeight, newWidth]` to resize the
* images to. Each channel is resized individually.
* @param alignCorners Defaults to False. If true, rescale
* input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4
* corners of images and resized images. If false, rescale by
* `new_height / height`. Treat similarly the width dimension.
* @param halfPixelCenters Defaults to `false`. Whether to assumes pixels are of
* half the actual dimensions, and yields more accurate resizes. This flag
* would also make the floating point coordinates of the top left pixel
* 0.5, 0.5.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function resizeNearestNeighbor_(images, size, alignCorners = false, halfPixelCenters = false) {
const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');
assert($images.rank === 3 || $images.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +
`rank ${$images.rank}.`);
assert(size.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +
`${size}.`);
assert($images.dtype === 'float32' || $images.dtype === 'int32', () => '`images` must have `int32` or `float32` as dtype');
assert(halfPixelCenters === false || alignCorners === false, () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +
`alignCorners must be false.`);
let batchImages = $images;
let reshapedTo4D = false;
if ($images.rank === 3) {
reshapedTo4D = true;
batchImages = reshape($images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);
}
const [] = size;
const inputs = { images: batchImages };
const attrs = { alignCorners, halfPixelCenters, size };
// tslint:disable-next-line: no-unnecessary-type-assertion
const res = ENGINE.runKernel(ResizeNearestNeighbor, inputs, attrs);
if (reshapedTo4D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]);
}
return res;
}
const resizeNearestNeighbor = op({ resizeNearestNeighbor_ });
/**
* @license
* Copyright 2021 Google LLC. 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* Performs image binarization with corresponding threshold
* (depends on the method)value, which creates a binary image from a grayscale.
* @param image 3d tensor of shape [imageHeight,imageWidth, depth],
* where imageHeight and imageWidth must be positive.The image color
* range should be [0, 255].
* @param method Optional string from `'binary' | 'otsu'`
* which specifies the method for thresholding. Defaults to 'binary'.
* @param inverted Optional boolean whichspecifies
* if colours should be inverted. Defaults to false.
* @param threshValue Optional number which defines threshold value from 0 to 1.
* Defaults to 0.5.
* @return A 3d tensor of shape [imageHeight,imageWidth, depth], which
* contains binarized image.
*/
function threshold_(image, method = 'binary', inverted = false, threshValue = 0.5) {
const $image = convertToTensor(image, 'image', 'threshold');
/* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.
Reference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29 */
const RED_INTENCITY_COEF = 0.2989;
const GREEN_INTENCITY_COEF = 0.5870;
const BLUE_INTENCITY_COEF = 0.1140;
const totalPixelsInImage = $image.shape[0] * $image.shape[1];
let $threshold = mul(tensor1d([threshValue]), 255);
let r, g, b, grayscale;
assert($image.rank === 3, () => 'Error in threshold: image must be rank 3,' +
`but got rank ${$image.rank}.`);
assert($image.shape[2] === 3 || $image.shape[2] === 1, () => 'Error in threshold: ' +
'image color channel must be equal to 3 or 1' +
`but got ${$image.shape[2]}.`);
assert($image.dtype === 'int32' || $image.dtype === 'float32', () => 'Error in dtype: image dtype must be int32 or float32,' +
`but got dtype ${$image.dtype}.`);
assert(method === 'otsu' || method === 'binary', () => `Method must be binary or otsu, but was ${method}`);
if ($image.shape[2] === 3) {
[r, g, b] = split($image, [1, 1, 1], -1);
const $r = mul(r, RED_INTENCITY_COEF);
const $g = mul(g, GREEN_INTENCITY_COEF);
const $b = mul(b, BLUE_INTENCITY_COEF);
grayscale = add$1(add$1($r, $g), $b);
}
else {
grayscale = image;
}
if (method === 'otsu') {
const $histogram = bincount(cast(round$1(grayscale), 'int32'), tensor([]), 256);
$threshold = otsu($histogram, totalPixelsInImage);
}
const invCondition = inverted ?
lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);
const result = cast(mul(invCondition, 255), 'int32');
return result;
}
function otsu(histogram, total) {
let bestThresh = tensor1d([-1]);
let bestInBetVar = tensor1d([0]);
let cInBetVar = tensor1d([0]);
let classFirst, classSecond, meanFirst, meanSec, weightForeground, weightBack;
for (let index = 0; index < histogram.size - 1; index++) {
classFirst = slice(histogram, 0, index + 1);
classSecond = slice(histogram, index + 1);
weightForeground = div(sum$1(classFirst), total);
weightBack = div(sum$1(classSecond), total);
const meanFirstDivA = sum$1(mul(classFirst, range(0, classFirst.size)));
meanFirst = div(meanFirstDivA, sum$1(classFirst));
const meanSecFill = fill(classSecond.shape, classFirst.size);
const meanSecAdd = add$1(range(0, classSecond.size), meanSecFill);
const meanSecMul = mul(classSecond, (meanSecAdd));
meanSec = div(sum$1(meanSecMul), sum$1(classSecond));
const cInBetVarSubA = sub(meanFirst, meanSec);
const cInBetVarSubB = sub(meanFirst, meanSec);
const cInBetVarMul = mul(weightForeground, weightBack);
cInBetVar = mul(mul(cInBetVarMul, cInBetVarSubA), cInBetVarSubB);
const condition = greater(cInBetVar, bestInBetVar);
bestInBetVar = where(condition, cInBetVar, bestInBetVar);
bestThresh = where(condition, tensor1d([index]), bestThresh);
}
return bestThresh;
}
const threshold = op({ threshold_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Applies the given transform(s) to the image(s).
*
* @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.
* @param transforms Projective transform matrix/matrices. A tensor1d of length
* 8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0
* b1, b2, c0, c1], then it maps the output point (x, y) to a transformed
* input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),
* where k = c0 x + c1 y + 1. The transforms are inverted compared to the
* transform mapping input points to output points.
* @param interpolation Interpolation mode.
* Supported values: 'nearest', 'bilinear'. Default to 'nearest'.
* @param fillMode Points outside the boundaries of the input are filled
* according to the given mode, one of 'constant', 'reflect', 'wrap',
* 'nearest'. Default to 'constant'.
* 'reflect': (d c b a | a b c d | d c b a ) The input is extended by
* reflecting about the edge of the last pixel.
* 'constant': (k k k k | a b c d | k k k k) The input is extended by
* filling all values beyond the edge with the same constant value k.
* 'wrap': (a b c d | a b c d | a b c d) The input is extended by
* wrapping around to the opposite edge.
* 'nearest': (a a a a | a b c d | d d d d) The input is extended by
* the nearest pixel.
* @param fillValue A float represents the value to be filled outside the
* boundaries when fillMode is 'constant'.
* @param Output dimension after the transform, [height, width]. If undefined,
* output is the same size as input image.
*
* @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}
*/
function transform_(image, transforms, interpolation = 'nearest', fillMode = 'constant', fillValue = 0, outputShape) {
const $image = convertToTensor(image, 'image', 'transform', 'float32');
const $transforms = convertToTensor(transforms, 'transforms', 'transform', 'float32');
assert($image.rank === 4, () => 'Error in transform: image must be rank 4,' +
`but got rank ${$image.rank}.`);
assert($transforms.rank === 2 &&
($transforms.shape[0] === $image.shape[0] ||
$transforms.shape[0] === 1) &&
$transforms.shape[1] === 8, () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);
assert(outputShape == null || outputShape.length === 2, () => 'Error in transform: outputShape must be [height, width] or null, ' +
`but got ${outputShape}.`);
const inputs = { image: $image, transforms: $transforms };
const attrs = { interpolation, fillMode, fillValue, outputShape };
return ENGINE.runKernel(Transform, inputs, attrs);
}
const transform = op({ transform_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Copy a tensor setting everything outside a central band in each innermost
* matrix to zero.
*
* The band part is computed as follows: Assume input has `k` dimensions
* `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where
* `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.
* The indicator function
* `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower))`
* `&& (num_upper < 0 || (n-m) <= num_upper)`
*
* ```js
* const x = tf.tensor2d([[ 0, 1, 2, 3],
* [-1, 0, 1, 2],
* [-2, -1, 0, 1],
* [-3, -2, -1, 0]]);
* let y = tf.linalg.bandPart(x, 1, -1);
* y.print(); // [[ 0, 1, 2, 3],
* // [-1, 0, 1, 2],
* // [ 0, -1, 0, 1],
* // [ 0, 0 , -1, 0]]
* let z = tf.linalg.bandPart(x, 2, 1);
* z.print(); // [[ 0, 1, 0, 0],
* // [-1, 0, 1, 0],
* // [-2, -1, 0, 1],
* // [ 0, -2, -1, 0]]
* ```
*
* @param x Rank `k` tensor
* @param numLower Number of subdiagonals to keep.
* If negative, keep entire lower triangle.
* @param numUpper Number of subdiagonals to keep.
* If negative, keep entire upper triangle.
* @returns Rank `k` tensor of the same shape as input.
* The extracted banded tensor.
*
* @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}
*/
function bandPart_(a, numLower, numUpper) {
assert(numLower % 1 === 0, () => `bandPart(): numLower must be an integer, got ${numLower}.`);
assert(numUpper % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);
const $a = convertToTensor(a, 'a', 'bandPart');
assert($a.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);
const shape = $a.shape;
const [M, N] = $a.shape.slice(-2);
if (!(numLower <= M)) {
throw new Error(`bandPart(): numLower (${numLower})` +
` must not be greater than the number of rows (${M}).`);
}
if (!(numUpper <= N)) {
throw new Error(`bandPart(): numUpper (${numUpper})` +
` must not be greater than the number of columns (${N}).`);
}
if (numLower < 0) {
numLower = M;
}
if (numUpper < 0) {
numUpper = N;
}
const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);
const j = range(0, N, 1, 'int32');
const ij = sub(i, j);
const inBand = logicalAnd(lessEqual(ij, scalar(+numLower, 'int32')), greaterEqual(ij, scalar(-numUpper, 'int32')));
const zero = zeros([M, N], $a.dtype);
return reshape(stack(unstack(reshape($a, [-1, M, N]))
.map(mat => where(inBand, mat, zero))), shape);
}
const bandPart = op({ bandPart_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Gram-Schmidt orthogonalization.
*
* ```js
* const x = tf.tensor2d([[1, 2], [3, 4]]);
* let y = tf.linalg.gramSchmidt(x);
* y.print();
* console.log('Othogonalized:');
* y.dot(y.transpose()).print(); // should be nearly the identity matrix.
* console.log('First row direction maintained:');
* const data = await y.array();
* console.log(data[0][1] / data[0][0]); // should be nearly 2.
* ```
*
* @param xs The vectors to be orthogonalized, in one of the two following
* formats:
* - An Array of `tf.Tensor1D`.
* - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows
* of `xs`.
* In each case, all the vectors must have the same length and the length
* must be greater than or equal to the number of vectors.
* @returns The orthogonalized and normalized vectors or matrix.
* Orthogonalization means that the vectors or the rows of the matrix
* are orthogonal (zero inner products). Normalization means that each
* vector or each row of the matrix has an L2 norm that equals `1`.
*
* @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}
*/
function gramSchmidt_(xs) {
let inputIsTensor2D;
if (Array.isArray(xs)) {
inputIsTensor2D = false;
assert(xs != null && xs.length > 0, () => 'Gram-Schmidt process: input must not be null, undefined, or ' +
'empty');
const dim = xs[0].shape[0];
for (let i = 1; i < xs.length; ++i) {
assert(xs[i].shape[0] === dim, () => 'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +
`(${xs[i].shape[0]} vs. ${dim})`);
}
}
else {
inputIsTensor2D = true;
xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));
}
assert(xs.length <= xs[0].shape[0], () => `Gram-Schmidt: Number of vectors (${xs.length}) exceeds ` +
`number of dimensions (${xs[0].shape[0]}).`);
const ys = [];
const xs1d = xs;
for (let i = 0; i < xs.length; ++i) {
ys.push(ENGINE.tidy(() => {
let x = xs1d[i];
if (i > 0) {
for (let j = 0; j < i; ++j) {
const proj = mul(sum$1(mul(ys[j], x)), ys[j]);
x = sub(x, proj);
}
}
return div(x, norm(x, 'euclidean'));
}));
}
if (inputIsTensor2D) {
return stack(ys, 0);
}
else {
return ys;
}
}
const gramSchmidt = op({ gramSchmidt_ });
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
/**
* Enables production mode which disables correctness checks in favor of
* performance.
*
* @doc {heading: 'Environment'}
*/
function enableProdMode() {
env().set('PROD', true);
}
/**
* Enables debug mode which will log information about all executed kernels:
* the elapsed time of the kernel execution, as well as the rank, shape, and
* size of the output tensor.
*
* Debug mode will significantly slow down your application as it will
* download the result of every operation to the CPU. This should not be used in
* production. Debug mode does not affect the timing information of the kernel
* execution as we do not measure download time in the kernel execution time.
*
* See also: `tf.profile`, `tf.memory`.
*
* @doc {heading: 'Environment'}
*/
function enableDebugMode() {
env().set('DEBUG', true);
}
/** Globally disables deprecation warnings */
function disableDeprecationWarnings() {
env().set('DEPRECATION_WARNINGS_ENABLED', false);
console.warn(`TensorFlow.js deprecation warnings have been disabled.`);
}
/** Warn users about deprecated functionality. */
function deprecationWarn(msg) {
if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {
console.warn(msg + ' You can disable deprecation warnings with ' +
'tf.disableDeprecationWarnings().');
}
}
setDeprecationWarningFn(deprecationWarn);
/**
* Dispose all variables kept in backend engine.
*
* @doc {heading: 'Environment'}
*/
function disposeVariables() {
ENGINE.disposeVariables();
}
/**
* It returns the global engine that keeps track of all tensors and backends.
*
* @doc {heading: 'Environment'}
*/
function engine() {
return ENGINE;
}
/**
* Returns memory info at the current time in the program. The result is an
* object with the following properties:
*
* - `numBytes`: Number of bytes allocated (undisposed) at this time.
* - `numTensors`: Number of unique tensors allocated.
* - `numDataBuffers`: Number of unique data buffers allocated
* (undisposed) at this time, which is ≤ the number of tensors
* (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same
* data buffer with `a`).
* - `unreliable`: True if the memory usage is unreliable. See `reasons` when
* `unreliable` is true.
* - `reasons`: `string[]`, reasons why the memory is unreliable, present if
* `unreliable` is true.
*
* WebGL Properties:
* - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at
* this time.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function memory() {
return ENGINE.memory();
}
/**
* Executes the provided function `f()` and returns a promise that resolves
* with information about the function's memory use:
* - `newBytes`: the number of new bytes allocated
* - `newTensors`: the number of new tensors created
* - `peakBytes`: the peak number of bytes allocated
* - `kernels`: an array of objects for each kernel involved that reports
* their input and output shapes, number of bytes used, and number of new
* tensors created.
* - `kernelNames`: an array of unique strings with just the names of the
* kernels in the `kernels` array.
*
* ```js
* const profile = await tf.profile(() => {
* const x = tf.tensor1d([1, 2, 3]);
* let x2 = x.square();
* x2.dispose();
* x2 = x.square();
* x2.dispose();
* return x;
* });
*
* console.log(`newBytes: ${profile.newBytes}`);
* console.log(`newTensors: ${profile.newTensors}`);
* console.log(`byte usage over all kernels: ${profile.kernels.map(k =>
* k.totalBytesSnapshot)}`);
* ```
*
*
* @doc {heading: 'Performance', subheading: 'Profile'}
*/
function profile(f) {
return ENGINE.profile(f);
}
/**
* Executes the provided function `fn` and after it is executed, cleans up all
* intermediate tensors allocated by `fn` except those returned by `fn`.
* `fn` must not return a Promise (async functions not allowed). The returned
* result can be a complex object.
*
* Using this method helps avoid memory leaks. In general, wrap calls to
* operations in `tf.tidy` for automatic memory cleanup.
*
* NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to
* dispose variables, please use `tf.disposeVariables` or call dispose()
* directly on variables.
*
* ```js
* // y = 2 ^ 2 + 1
* const y = tf.tidy(() => {
* // a, b, and one will be cleaned up when the tidy ends.
* const one = tf.scalar(1);
* const a = tf.scalar(2);
* const b = a.square();
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* y.print();
* ```
*
* @param nameOrFn The name of the closure, or the function to execute.
* If a name is provided, the 2nd argument should be the function.
* If debug mode is on, the timing and the memory usage of the function
* will be tracked and displayed on the console using the provided name.
* @param fn The function to execute.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function tidy(nameOrFn, fn) {
return ENGINE.tidy(nameOrFn, fn);
}
/**
* Disposes any `tf.Tensor`s found within the provided object.
*
* @param container an object that may be a `tf.Tensor` or may directly
* contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If
* the object is not a `tf.Tensor` or does not contain `Tensors`, nothing
* happens. In general it is safe to pass any object here, except that
* `Promise`s are not supported.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function dispose(container) {
const tensors = getTensorsInContainer(container);
tensors.forEach(tensor => tensor.dispose());
}
/**
* Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed
* automatically.
*
* ```js
* let b;
* const y = tf.tidy(() => {
* const one = tf.scalar(1);
* const a = tf.scalar(2);
*
* // b will not be cleaned up by the tidy. a and one will be cleaned up
* // when the tidy ends.
* b = tf.keep(a.square());
*
* console.log('numTensors (in tidy): ' + tf.memory().numTensors);
*
* // The value returned inside the tidy function will return
* // through the tidy, in this case to the variable y.
* return b.add(one);
* });
*
* console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
* console.log('y:');
* y.print();
* console.log('b:');
* b.print();
* ```
*
* @param result The tensor to keep from being disposed.
*
* @doc {heading: 'Performance', subheading: 'Memory'}
*/
function keep(result) {
return ENGINE.keep(result);
}
/**
* Executes `f()` and returns a promise that resolves with timing
* information.
*
* The result is an object with the following properties:
*
* - `wallMs`: Wall execution time.
* - `kernelMs`: Kernel execution time, ignoring data transfer. If using the
* WebGL backend and the query timer extension is not available, this will
* return an error object.
* - On `WebGL` The following additional properties exist:
* - `uploadWaitMs`: CPU blocking time on texture uploads.
* - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).
*
* ```js
* const x = tf.randomNormal([20, 20]);
* const time = await tf.time(() => x.matMul(x));
*
* console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);
* ```
*
* @param f The function to execute and time.
*
* @doc {heading: 'Performance', subheading: 'Timing'}
*/
function time(f) {
return ENGINE.time(f);
}
/**
* Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and
* executing operations on those tensors. Returns a promise that resolves
* to a boolean if the backend initialization was successful.
*
* Note this disposes the current backend, if any, as well as any tensors
* associated with it. A new backend is initialized, even if it is of the
* same type as the previous one.
*
* @param backendName The name of the backend. Currently supports
* `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js
* (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).
*
* @doc {heading: 'Backends'}
*/
function setBackend(backendName) {
return ENGINE.setBackend(backendName);
}
/**
* Returns a promise that resolves when the currently selected backend (or the
* highest priority one) has initialized. Await this promise when you are using
* a backend that has async initialization.
*
* @doc {heading: 'Backends'}
*/
function ready() {
return ENGINE.ready();
}
/**
* Returns the current backend name (cpu, webgl, etc). The backend is
* responsible for creating tensors and executing operations on those tensors.
*
* @doc {heading: 'Backends'}
*/
function getBackend() {
return ENGINE.backendName;
}
/**
* Removes a backend and the registered factory.
*
* @doc {heading: 'Backends'}
*/
function removeBackend(name) {
ENGINE.removeBackend(name);
}
/**
* Finds the backend registered under the provided name. Returns null if the
* name is not in the registry, or the registration hasn't finished yet.
*/
function findBackend(name) {
return ENGINE.findBackend(name);
}
/**
* Finds the backend factory registered under the provided name. Returns a
* function that produces a new backend when called. Returns null if the name
* is not in the registry.
*/
function findBackendFactory(name) {
return ENGINE.findBackendFactory(name);
}
/**
* Registers a global backend. The registration should happen when importing
* a module file (e.g. when importing `backend_webgl.ts`), and is used for
* modular builds (e.g. custom tfjs bundle with only webgl support).
*
* @param factory The backend factory function. When called, it should
* return a backend instance, or a promise of an instance.
* @param priority The priority of the backend (higher = more important).
* In case multiple backends are registered, the priority is used to find
* the best backend. Defaults to 1.
* @return False if there is already a registered backend under this name, true
* if not.
*
* @doc {heading: 'Backends'}
*/
function registerBackend(name, factory, priority = 1) {
return ENGINE.registerBackend(name, factory, priority);
}
/**
* Gets the current backend. If no backends have been initialized, this will
* attempt to initialize the best backend. Will throw an error if the highest
* priority backend has async initialization, in which case, you should call
* 'await tf.ready()' before running other code.
*
* @doc {heading: 'Backends'}
*/
function backend() {
return ENGINE.backend;
}
/**
* Sets the global platform.
*
* @param platformName The name of this platform.
* @param platform A platform implementation.
*/
function setPlatform(platformName, platform) {
env().setPlatform(platformName, platform);
}
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Compute QR decomposition of m-by-n matrix using Householder transformation.
*
* Implementation based on
* [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]
* (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)
*
* ```js
* const a = tf.tensor2d([[1, 2], [3, 4]]);
* let [q, r] = tf.linalg.qr(a);
* console.log('Q');
* q.print();
* console.log('R');
* r.print();
* console.log('Orthogonalized');
* q.dot(q.transpose()).print() // should be nearly the identity matrix.
* console.log('Reconstructed');
* q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];
* ```
*
* @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose
* it has the shape `[..., M, N]`.
* @param fullMatrices An optional boolean parameter. Defaults to `false`.
* If `true`, compute full-sized `Q`. If `false` (the default),
* compute only the leading N columns of `Q` and `R`.
* @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,
* i.e., its columns all have unit norm and are mutually orthogonal.
* If `M >= N`,
* If `fullMatrices` is `false` (default),
* - `Q` has a shape of `[..., M, N]`,
* - `R` has a shape of `[..., N, N]`.
* If `fullMatrices` is `true` (default),
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* If `M < N`,
* - `Q` has a shape of `[..., M, M]`,
* - `R` has a shape of `[..., M, N]`.
* @throws If the rank of `x` is less than 2.
*
* @doc {heading:'Operations',
* subheading:'Linear Algebra',
* namespace:'linalg'}
*/
function qr_(x, fullMatrices = false) {
assert(x.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${x.rank}`);
if (x.rank === 2) {
return qr2d(x, fullMatrices);
}
else {
// Rank > 2.
// TODO(cais): Below we split the input into individual 2D tensors,
// perform QR decomposition on them and then stack the results back
// together. We should explore whether this can be parallelized.
const outerDimsProd = x.shape.slice(0, x.shape.length - 2)
.reduce((value, prev) => value * prev);
const x2ds = unstack(reshape(x, [
outerDimsProd, x.shape[x.shape.length - 2],
x.shape[x.shape.length - 1]
]), 0);
const q2ds = [];
const r2ds = [];
x2ds.forEach(x2d => {
const [q2d, r2d] = qr2d(x2d, fullMatrices);
q2ds.push(q2d);
r2ds.push(r2d);
});
const q = reshape(stack(q2ds, 0), x.shape);
const r = reshape(stack(r2ds, 0), x.shape);
return [q, r];
}
}
function qr2d(x, fullMatrices = false) {
return ENGINE.tidy(() => {
assert(x.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${x.shape.length}D Tensor.`);
const m = x.shape[0];
const n = x.shape[1];
let q = eye(m); // Orthogonal transform so far.
let r = clone(x); // Transformed matrix so far.
const one2D = tensor2d([[1]], [1, 1]);
let w = clone(one2D);
const iters = m >= n ? n : m;
for (let j = 0; j < iters; ++j) {
// This tidy within the for-loop ensures we clean up temporary
// tensors as soon as they are no longer needed.
const rTemp = r;
const wTemp = w;
const qTemp = q;
[w, r, q] = ENGINE.tidy(() => {
// Find H = I - tau * w * w', to put zeros below R(j, j).
const rjEnd1 = slice(r, [j, j], [m - j, 1]);
const normX = norm(rjEnd1);
const rjj = slice(r, [j, j], [1, 1]);
// The sign() function returns 0 on 0, which causes division by zero.
const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));
const u1 = sub(rjj, mul(s, normX));
const wPre = div(rjEnd1, u1);
if (wPre.shape[0] === 1) {
w = clone(one2D);
}
else {
w = concat([
one2D,
slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]])
], 0);
}
const tau = neg(div(matMul(s, u1), normX));
// -- R := HR, Q := QH.
const rjEndAll = slice(r, [j, 0], [m - j, n]);
const tauTimesW = mul(tau, w);
const wT = transpose(w);
if (j === 0) {
r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));
}
else {
const rTimesTau = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));
r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);
}
const tawTimesWT = transpose(tauTimesW);
const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);
if (j === 0) {
q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));
}
else {
const qTimesTau = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));
q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);
}
return [w, r, q];
});
dispose([rTemp, wTemp, qTemp]);
}
if (!fullMatrices && m > n) {
q = slice(q, [0, 0], [m, n]);
r = slice(r, [0, 0], [n, n]);
}
return [q, r];
});
}
const qr = op({ qr_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
var Reduction;
(function (Reduction) {
Reduction[Reduction["NONE"] = 0] = "NONE";
Reduction[Reduction["MEAN"] = 1] = "MEAN";
Reduction[Reduction["SUM"] = 2] = "SUM";
Reduction[Reduction["SUM_BY_NONZERO_WEIGHTS"] = 3] = "SUM_BY_NONZERO_WEIGHTS";
})(Reduction || (Reduction = {}));
/**
* Computes the weighted loss between two tensors.
*
* @param losses Tensor of shape `[batch_size, d1, ... dN]`.
* @param weights Tensor whose rank is either 0, or the same rank as
* `losses`, and must be broadcastable to `losses` (i.e., all
* dimensions must be either `1`, or the same as the corresponding
* `losses` dimension).
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function computeWeightedLoss_(losses, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $losses = convertToTensor(losses, 'losses', 'computeWeightedLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'computeWeightedLoss');
}
const weightedLoss = ($weights == null) ? $losses : mul($losses, $weights);
if (reduction === Reduction.NONE) {
return weightedLoss;
}
if (reduction === Reduction.SUM) {
return sum$1(weightedLoss);
}
if (reduction === Reduction.MEAN) {
if ($weights == null) {
return mean(weightedLoss);
}
else {
const broadcastFactor = $losses.size / $weights.size;
const result = div(sum$1(weightedLoss), sum$1($weights));
return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) :
result;
}
}
if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {
if ($weights == null) {
return div(sum$1(weightedLoss), scalar($losses.size));
}
else {
const broadcastedWeights = mul($weights, ones$1($losses.shape));
const numNonZeros = cast(sum$1(notEqual(broadcastedWeights, scalar(0))), 'float32');
return div(sum$1(weightedLoss), numNonZeros);
}
}
throw Error(`Unknown reduction: ${reduction}`);
}
const computeWeightedLoss = op({ computeWeightedLoss_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the absolute difference loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function absoluteDifference_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'absoluteDifference');
const $predictions = convertToTensor(predictions, 'predictions', 'absoluteDifference');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'absoluteDifference');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in absoluteDifference: ');
const losses = abs(sub($labels, $predictions));
return computeWeightedLoss(losses, $weights, reduction);
}
const absoluteDifference = op({ absoluteDifference_ });
/**
* Computes the cosine distance loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param axis The dimension along which the cosine distance is computed.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function cosineDistance_(labels, predictions, axis, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'cosineDistance');
const $predictions = convertToTensor(predictions, 'predictions', 'cosineDistance');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'cosineDistance');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in cosineDistance: ');
const one = scalar(1);
const losses = sub(one, sum$1(mul($labels, $predictions), axis, true));
return computeWeightedLoss(losses, $weights, reduction);
}
const cosineDistance = op({ cosineDistance_ });
/**
* Computes the Hinge loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function hingeLoss_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $labels = convertToTensor(labels, 'labels', 'hingeLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'hingeLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');
const one = scalar(1);
// Convert binary labels to (-1, 1)
$labels = sub(mul(scalar(2), $labels), one);
const losses = relu(sub(one, mul($labels, $predictions)));
return computeWeightedLoss(losses, $weights, reduction);
}
const hingeLoss = op({ hingeLoss_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the huber loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param delta Point where huber loss changes from quadratic to linear.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`.
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function huberLoss_(labels, predictions, weights, delta = 1.0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'huberLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'huberLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'huberLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in huberLoss: ');
const deltaScalar = scalar(delta);
const error = abs(sub($predictions, $labels));
const quadratic = minimum(error, deltaScalar);
const linear = sub(error, quadratic);
const losses = add$1(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));
return computeWeightedLoss(losses, $weights, reduction);
}
const huberLoss = op({ huberLoss_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the log loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param epsilon A small increment to avoid taking log of zero
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function logLoss_(labels, predictions, weights, epsilon = 1e-7, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'logLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'logLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');
const one = scalar(1);
const epsilonScalar = scalar(epsilon);
const l1 = neg(mul($labels, log$1(add$1($predictions, epsilonScalar))));
const l2 = mul(sub(one, $labels), log$1(add$1(sub(one, $predictions), epsilonScalar)));
const losses = sub(l1, l2);
return computeWeightedLoss(losses, $weights, reduction);
}
const logLoss = op({ logLoss_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the mean squared error between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function meanSquaredError_(labels, predictions, weights, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
const $labels = convertToTensor(labels, 'labels', 'meanSquaredError');
const $predictions = convertToTensor(predictions, 'predictions', 'meanSquaredError');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'meanSquaredError');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in meanSquaredError: ');
const losses = squaredDifference($labels, $predictions);
return computeWeightedLoss(losses, $weights, reduction);
}
const meanSquaredError = op({ meanSquaredError_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
function sigmoidCrossEntropyWithLogits_(labels, logits) {
const $labels = convertToTensor(labels, 'labels', 'sigmoidCrossEntropyWithLogits');
const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropyWithLogits');
assertShapesMatch($labels.shape, $logits.shape, 'Error in sigmoidCrossEntropyWithLogits: ');
/**
* Implementation Details:
*
* For brevity, let `x = logits`, `z = labels`. The logistic loss is
* z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
* = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
* = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
* = (1 - z) * x + log(1 + exp(-x))
* = x - x * z + log(1 + exp(-x))
*
* For x < 0, to avoid overflow in exp(-x), we reformulate the above
* x - x * z + log(1 + exp(-x))
* = log(exp(x)) - x * z + log(1 + exp(-x))
* = - x * z + log(1 + exp(x))
*
* Hence, to ensure stability and avoid overflow, the implementation uses
* this equivalent formulation:
* max(x, 0) - x * z + log(1 + exp(-abs(x)))
*/
const maxOutput = relu($logits);
const outputXTarget = mul($logits, $labels);
const sigmoidOutput = log1p(exp(neg(abs($logits))));
return add$1(sub(maxOutput, outputXTarget), sigmoidOutput);
}
/**
* Computes the sigmoid cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newMulticlassLabels = multiclassLabels * (1 - labelSmoothing)
* + 0.5 * labelSmoothing
*
* @param multiClassLabels The ground truth output tensor of shape
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }
*/
function sigmoidCrossEntropy_(multiClassLabels, logits, weights, labelSmoothing = 0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $multiClassLabels = convertToTensor(multiClassLabels, 'multiClassLabels', 'sigmoidCrossEntropy');
const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropy');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'sigmoidCrossEntropy');
}
assertShapesMatch($multiClassLabels.shape, $logits.shape, 'Error in sigmoidCrossEntropy: ');
if (labelSmoothing > 0) {
const labelSmoothingScalar = scalar(labelSmoothing);
const one = scalar(1);
const half = scalar(0.5);
$multiClassLabels =
add$1(mul($multiClassLabels, sub(one, labelSmoothingScalar)), mul(half, labelSmoothingScalar));
}
const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
const sigmoidCrossEntropy = op({ sigmoidCrossEntropy_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Computes softmax cross entropy between logits and labels.
*
* Measures the probability error in discrete classification tasks in which
* the classes are mutually exclusive (each entry is in exactly one class).
* For example, each CIFAR-10 image is labeled with one and only one label: an
* image can be a dog or a truck, but not both.
*
* `NOTE`: While the classes are mutually exclusive, their probabilities need
* not be. All that is required is that each row of labels is a valid
* probability distribution. If they are not, the computation of the gradient
* will be incorrect.
*
* `WARNING`: This op expects unscaled logits, since it performs a softmax on
* logits internally for efficiency. Do not call this op with the output of
* softmax, as it will produce incorrect results.
*
* logits and labels must have the same shape, e.g. [batch_size, num_classes]
* and the same dtype.
* @param labels The labels array.
* @param logits The logits array.
* @param dim The dimension softmax would be performed on. Defaults to `-1`
* which indicates the last dimension.
*/
function softmaxCrossEntropyWithLogits_(labels, logits, dim = -1) {
if (dim === -1) {
dim = logits.rank - 1;
}
if (dim !== logits.rank - 1) {
throw Error(`Softmax cross entropy along a non-last dimension is not yet ` +
`supported. Labels / logits was rank ${logits.rank} ` +
`and dim was ${dim}`);
}
// Use a custom gradient for numerical stability.
const customOp = customGrad((labels, logits, save) => {
// Reference:
// 1. http://cs231n.github.io/linear-classify/#softmax
// 2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/
const keepDims = true;
const lse = logSumExp(logits, [dim], keepDims);
const logResult = sub(cast(logits, 'float32'), lse);
save([labels, logResult]);
const costVector = neg(mul(logResult, labels));
const value = sum$1(costVector, [dim]);
const gradFunc = (dy, saved) => {
const [labels, logResult] = saved;
const dyShape = expandShapeToKeepDim(dy.shape, [dim]);
return [
mul(reshape(dy, dyShape), sub(cast(labels, 'float32'), exp(logResult))),
mul(reshape(dy, dyShape), sub(exp(logResult), cast(labels, 'float32'))),
];
};
return { value, gradFunc };
});
return customOp(labels, logits);
}
/**
* Computes the softmax cross entropy loss between two tensors.
*
* If labelSmoothing is nonzero, smooth the labels towards 1/2:
*
* newOnehotLabels = onehotLabels * (1 - labelSmoothing)
* + labelSmoothing / numClasses
*
* @param onehotLabels One hot encoded labels
* [batch_size, num_classes], same dimensions as 'predictions'.
* @param logits The predicted outputs.
* @param weights Tensor whose rank is either 0, or 1, and must be
* broadcastable to `loss` of shape [batch_size]
* @param labelSmoothing If greater than 0, then smooth the labels.
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }
*/
function softmaxCrossEntropy_(onehotLabels, logits, weights, labelSmoothing = 0, reduction = Reduction.SUM_BY_NONZERO_WEIGHTS) {
let $onehotLabels = convertToTensor(onehotLabels, 'onehotLabels', 'softmaxCrossEntropy');
const $logits = convertToTensor(logits, 'logits', 'softmaxCrossEntropy');
let $weights = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'softmaxCrossEntropy');
}
assertShapesMatch($onehotLabels.shape, $logits.shape, 'Error in softmaxCrossEntropy: ');
if (labelSmoothing > 0) {
const labelSmoothingScalar = scalar(labelSmoothing);
const one = scalar(1);
const numClasses = scalar($onehotLabels.shape[1]);
$onehotLabels =
add$1(mul($onehotLabels, sub(one, labelSmoothingScalar)), div(labelSmoothingScalar, numClasses));
}
const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);
return computeWeightedLoss(losses, $weights, reduction);
}
const softmaxCrossEntropy = op({ softmaxCrossEntropy_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* The input SparseTensor is represented via the map of inputs {`indices`,
* `values`, `denseShape`}. The output SparseTensor has the same `denseShape`
* but with indices `outputIndices` and values `outputValues`. This op inserts a
* single entry for every row that doesn't have any values. The index is created
* as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.
*
* For example, suppose `spInput` has shape [5, 6] and non-empty values:
* [0, 1]: a
* [0, 3]: b
* [2, 0]: c
* [3, 1]: d
*
* Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:
* [0, 1]: a
* [0, 3]: b
* [1, 0]: `defaultValue`
* [2, 0]: c
* [3, 1]: d
* [4, 0]: `defaultValue`
*
* The output SparseTensor will be in row-major order and will have the same
* shape as the input.
*
* This op also returns an indicator vector shaped [dense_shape[0]] such that
* emptyRowIndicator[i] = True iff row i was an empty row.
*
* And a reverse index map vector shaped [indices.shape[0]] that is used during
* backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==
* outputIndices[outi, j] for all j
*
* ```js
* const result = tf.sparse.sparseFillEmptyRows(
* [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],
* [0, 10, 13, 14, 32, 33], [5, 6], -1);
* console.log(result);
* result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],
* // [2, 0], [3, 2], [3, 3], [4, 0]]
* result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]
* result['emptyRowIndicator'].print(); // [false, false, true, false, true]
* result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]
* ```
* @param indices: 2-D. the indices of the sparse tensor.
* @param values: 1-D. the values of the sparse tensor.
* @param denseShape: 1-D. the shape of the sparse tensor.
* @param defaultValue: 0-D. default value to insert into location [row, 0, ...,
* 0] for rows missing from the input sparse tensor.
* @return A map with the following properties:
* - outputIndices
* - outputValues: 1-D. the values of the filled sparse tensor.
* - emptyRowIndicator: 1-D. whether the dense row was missing in the input
* sparse tensor.
* - reverseIndexMap: 1-D. a map from the input indices to the output
* indices.
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseFillEmptyRows_(indices, values, denseShape, defaultValue) {
const $indices = convertToTensor(indices, 'indices', 'sparseFillEmptyRows');
const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');
const $denseShape = convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows');
const $defaultValue = convertToTensor(defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);
if ($indices.rank !== 2) {
throw new Error(`Indices should be Tensor2D but received shape
${$indices.shape}`);
}
if ($values.rank !== 1) {
throw new Error(`Values should be Tensor1D but received shape ${$values.shape}`);
}
if ($denseShape.rank !== 1) {
throw new Error(`Dense shape should be Tensor1D but received shape ${$denseShape.shape}`);
}
if ($defaultValue.rank !== 0) {
throw new Error(`Default value should be a scalar but received shape ${$defaultValue.shape}`);
}
const inputs = {
indices: $indices,
values: $values,
denseShape: $denseShape,
defaultValue: $defaultValue
};
const result = ENGINE.runKernel(SparseFillEmptyRows, inputs);
return {
outputIndices: result[0],
outputValues: result[1],
emptyRowIndicator: result[2],
reverseIndexMap: result[3]
};
}
const sparseFillEmptyRows = op({ sparseFillEmptyRows_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* This operation has the same semantics as reshape on the represented dense
* tensor. The `inputIndices` are recomputed based on the requested `newShape`.
* If one component of `newShape` is the special value -1, the size of that
* dimension is computed so that the total dense size remains constant. At most
* one component of `newShape` can be -1. The number of dense elements implied
* by `newShape` must be the same as the number of dense elements originally
* implied by `inputShape`. Reshaping does not affect the order of values in the
* SparseTensor. If the input tensor has rank R_in and N non-empty values, and
* `newShape` has length R_out, then `inputIndices` has shape [N, R_in],
* `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and
* `outputShape` has length R_out.
*
* ```js
* const result = tf.sparse.sparseReshape(
* [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],
* [2, 3, 6], [9, -1]);
* console.log(result);
* result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]
* result['outputShape'].print(); // [9, 4]
* ```
* @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty
* values in a SparseTensor.
* @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense
* shape.
* @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.
* @return A map with the following properties:
* - outputIndices: 2-D. N x R_out matrix with the updated indices of
* non-empty values in the output SparseTensor.
* - outputShape: 1-D. R_out vector with the full dense shape of the output
* SparseTensor. This is the same as newShape but with any -1 dimensions
* filled in.
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseReshape_(inputIndices, inputShape, newShape) {
const $inputIndices = convertToTensor(inputIndices, 'inputIndices', 'sparseReshape');
const $inputShape = convertToTensor(inputShape, 'inputShape', 'sparseReshape');
const $newShape = convertToTensor(newShape, 'newShape', 'sparseReshape');
if ($inputIndices.rank !== 2) {
throw new Error(`Input indices should be Tensor2D but received shape
${$inputIndices.shape}`);
}
if ($inputShape.rank !== 1) {
throw new Error(`Input shape should be Tensor1D but received shape ${$inputShape.shape}`);
}
if ($newShape.rank !== 1) {
throw new Error(`New shape should be Tensor1D but received shape ${$newShape.shape}`);
}
const inputs = {
inputIndices: $inputIndices,
inputShape: $inputShape,
newShape: $newShape
};
const result = ENGINE.runKernel(SparseReshape, inputs);
return { outputIndices: result[0], outputShape: result[1] };
}
const sparseReshape = op({ sparseReshape_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the mean along sparse segments of a tensor.
*
* ```js
* const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);
* // Select two rows, one segment.
* const result1 = tf.sparse.sparseSegmentMean(c,
* tf.tensor1d([0, 1], 'int32'),
* tf.tensor1d([0, 0], 'int32'));
* result1.print(); // [[0, 0, 0, 0]]
*
* // Select two rows, two segments.
* const result2 = tf.sparse.sparseSegmentMean(c,
* tf.tensor1d([0, 1], 'int32'),
* tf.tensor1d([0, 1], 'int32'));
* result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]
*
* // Select all rows, two segments.
* const result3 = tf.sparse.sparseSegmentMean(c,
* tf.tensor1d([0, 1, 2], 'int32'),
* tf.tensor1d([0, 1, 1], 'int32'));
* result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]
* ```
* @param data: A Tensor of at least one dimension with data that will be
* assembled in the output.
* @param indices: A 1-D Tensor with indices into data. Has same rank as
* segmentIds.
* @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values
* should be sorted and can be repeated.
* @return Has same shape as data, except for dimension 0 which has equal to
* the number of segments.
*
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseSegmentMean_(data, indices, segmentIds) {
const $data = convertToTensor(data, 'data', 'sparseSegmentMean');
const $indices = convertToTensor(indices, 'indices', 'sparseSegmentMean');
const $segmentIds = convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean');
if ($data.rank < 1) {
throw new Error(`Data should be at least 1 dimensional but received scalar`);
}
if ($indices.rank !== 1) {
throw new Error(`Indices should be Tensor1D but received shape
${$indices.shape}`);
}
if ($segmentIds.rank !== 1) {
throw new Error(`Segment ids should be Tensor1D but received shape
${$segmentIds.shape}`);
}
const inputs = {
data: $data,
indices: $indices,
segmentIds: $segmentIds
};
return ENGINE.runKernel(SparseSegmentMean, inputs);
}
const sparseSegmentMean = op({ sparseSegmentMean_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Computes the sum along sparse segments of a tensor.
*
* ```js
* const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);
* // Select two rows, one segment.
* const result1 = tf.sparse.sparseSegmentSum(c,
* tf.tensor1d([0, 1], 'int32'),
* tf.tensor1d([0, 0], 'int32'));
* result1.print(); // [[0, 0, 0, 0]]
*
* // Select two rows, two segment.
* const result2 = tf.sparse.sparseSegmentSum(c,
* tf.tensor1d([0, 1], 'int32'),
* tf.tensor1d([0, 1], 'int32'));
* result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]
*
* // Select all rows, two segments.
* const result3 = tf.sparse.sparseSegmentSum(c,
* tf.tensor1d([0, 1, 2], 'int32'),
* tf.tensor1d([0, 0, 1], 'int32'));
* result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]
* ```
* @param data: A Tensor of at least one dimension with data that will be
* assembled in the output.
* @param indices: A 1-D Tensor with indices into data. Has same rank as
* segmentIds.
* @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values
* should be sorted and can be repeated.
* @return Has same shape as data, except for dimension 0 which has equal to
* the number of segments.
*
* @doc {heading: 'Operations', subheading: 'Sparse'}
*/
function sparseSegmentSum_(data, indices, segmentIds) {
const $data = convertToTensor(data, 'data', 'sparseSegmentSum');
const $indices = convertToTensor(indices, 'indices', 'sparseSegmentSum');
const $segmentIds = convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum');
if ($data.rank < 1) {
throw new Error(`Data should be at least 1 dimensional but received scalar`);
}
if ($indices.rank !== 1) {
throw new Error(`Indices should be Tensor1D but received shape
${$indices.shape}`);
}
if ($segmentIds.rank !== 1) {
throw new Error(`Segment ids should be Tensor1D but received shape
${$segmentIds.shape}`);
}
const inputs = {
data: $data,
indices: $indices,
segmentIds: $segmentIds
};
return ENGINE.runKernel(SparseSegmentSum, inputs);
}
const sparseSegmentSum = op({ sparseSegmentSum_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Creates ngrams from ragged string data.
*
* This op accepts a ragged tensor with 1 ragged dimension containing only
* strings and outputs a ragged tensor with 1 ragged dimension containing ngrams
* of that string, joined along the innermost axis.
*
* ```js
* const result = tf.string.stringNGrams(
* ['a', 'b', 'c', 'd'], tf.tensor1d([0, 2, 4], 'int32'),
* '|', [1, 2], 'LP', 'RP', -1, false);
* result['nGrams'].print(); // ['a', 'b', 'LP|a', 'a|b', 'b|RP',
* // 'c', 'd', 'LP|c', 'c|d', 'd|RP']
* result['nGramsSplits'].print(); // [0, 5, 10]
* ```
* @param data: The values tensor of the ragged string tensor to make ngrams out
* of. Must be a 1D string tensor.
* @param dataSplits: The splits tensor of the ragged string tensor to make
* ngrams out of.
* @param separator: The string to append between elements of the token. Use ""
* for no separator.
* @param nGramWidths: The sizes of the ngrams to create.
* @param leftPad: The string to use to pad the left side of the ngram sequence.
* Only used if pad_width !== 0.
* @param rightPad: The string to use to pad the right side of the ngram
* sequence. Only used if pad_width !== 0.
* @param padWidth: The number of padding elements to add to each side of each
* sequence. Note that padding will never be greater than `nGramWidths`-1
* regardless of this value. If `padWidth`=-1 , then add max(`nGramWidths)-1
* elements.
* @param preserveShortSequences: If true, then ensure that at least one ngram
* is generated for each input sequence. In particular, if an input sequence
* is shorter than min(ngramWidth) + 2*padWidth, then generate a single
* ngram containing the entire sequence. If false, then no ngrams are
* generated for these short input sequences.
* @return A map with the following properties:
* - nGrams: The values tensor of the output ngrams ragged tensor.
* - nGramsSplits: The splits tensor of the output ngrams ragged tensor.
*
* @doc {heading: 'Operations', subheading: 'String'}
*/
function stringNGrams_(data, dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth, preserveShortSequences) {
const $data = convertToTensor(data, 'data', 'stringNGrams', 'string');
if ($data.dtype !== 'string') {
throw new Error('Data must be of datatype string');
}
if ($data.shape.length !== 1) {
throw new Error(`Data must be a vector, saw: ${$data.shape}`);
}
const $dataSplits = convertToTensor(dataSplits, 'dataSplits', 'stringNGrams');
if ($dataSplits.dtype !== 'int32') {
throw new Error('Data splits must be of datatype int32');
}
const attrs = {
separator,
nGramWidths,
leftPad,
rightPad,
padWidth,
preserveShortSequences
};
const inputs = { data: $data, dataSplits: $dataSplits };
const result = ENGINE.runKernel(StringNGrams, inputs, attrs);
return { nGrams: result[0], nGramsSplits: result[1] };
}
const stringNGrams = op({ stringNGrams_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Split elements of `input` based on `delimiter` into a SparseTensor .
*
* Let N be the size of source (typically N will be the batch size). Split each
* element of `input` based on `delimiter` and return a SparseTensor containing
* the splitted tokens. Empty tokens are ignored if `skipEmpty` is set to True.
*
* `delimiter` can be empty, or a string of split characters. If `delimiter` is
* an empty string, each element of `input` is split into individual
* character strings. Otherwise every character of `delimiter` is a potential
* split point.
*
* ```js
* const result = tf.string.stringSplit(['hello world', 'a b c'], ' ');
* result['indices'].print(); // [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]]
* result['values'].print(); // ['hello', 'world', 'a', 'b', 'c']
* result['shape'].print(); // [2, 3]
* ```
* @param input: 1-D. Strings to split.
* @param delimiter: 0-D. Delimiter characters, or empty string.
* @param skipEmpty: Optional. If true, skip the empty strings from the result.
* Defaults to true.
* @return A map with the following properties:
* - indices: A dense matrix of int32 representing the indices of the sparse
* tensor.
* - values: A vector of strings corresponding to the splited values.
* - shape: a length-2 vector of int32 representing the shape of the sparse
* tensor, where the first value is N and the second value is the maximum number
* of tokens in a single input entry.
*
* @doc {heading: 'Operations', subheading: 'String'}
*/
function stringSplit_(input, delimiter, skipEmpty = true) {
const $input = convertToTensor(input, 'input', 'stringSplit', 'string');
const $delimiter = convertToTensor(delimiter, 'delimiter', 'stringSplit', 'string');
if ($input.rank !== 1) {
throw new Error(`Input should be Tensor1D but received shape ${$input.shape}`);
}
if ($delimiter.rank !== 0) {
throw new Error(`Delimiter should be a scalar but received shape ${$delimiter.shape}`);
}
const attrs = { skipEmpty };
const inputs = { input: $input, delimiter: $delimiter };
const result = ENGINE.runKernel(StringSplit, inputs, attrs);
return { indices: result[0], values: result[1], shape: result[2] };
}
const stringSplit = op({ stringSplit_ });
/**
* @license
* Copyright 2021 Google LLC. 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.
* =============================================================================
*/
/**
* Converts each string in the input Tensor to its hash mod by a number of
* buckets.
*
* The hash function is deterministic on the content of the string within the
* process and will never change. However, it is not suitable for cryptography.
* This function may be used when CPU time is scarce and inputs are trusted or
* unimportant. There is a risk of adversaries constructing inputs that all hash
* to the same bucket.
*
* ```js
* const result = tf.string.stringToHashBucketFast(
* ['Hello', 'TensorFlow', '2.x'], 3);
* result.print(); // [0, 2, 2]
* ```
* @param input: The strings to assign a hash bucket.
* @param numBuckets: The number of buckets.
* @return A Tensor of the same shape as the input tensor.
*
* @doc {heading: 'Operations', subheading: 'String'}
*/
function stringToHashBucketFast_(input, numBuckets) {
const $input = convertToTensor(input, 'input', 'stringToHashBucketFast', 'string');
const attrs = { numBuckets };
if (numBuckets <= 0) {
throw new Error(`Number of buckets must be at least 1`);
}
const inputs = { input: $input };
return ENGINE.runKernel(StringToHashBucketFast, inputs, attrs);
}
const stringToHashBucketFast = op({ stringToHashBucketFast_ });
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
const spectral = {
fft,
ifft,
rfft,
irfft
};
const signal = {
hammingWindow,
hannWindow,
frame,
stft,
};
const image = {
flipLeftRight,
grayscaleToRGB,
resizeNearestNeighbor,
resizeBilinear,
rotateWithOffset,
cropAndResize,
nonMaxSuppression,
nonMaxSuppressionAsync,
nonMaxSuppressionWithScore,
nonMaxSuppressionWithScoreAsync,
nonMaxSuppressionPadded,
nonMaxSuppressionPaddedAsync,
threshold,
transform
};
const linalg = {
bandPart,
gramSchmidt,
qr
};
const losses = {
absoluteDifference,
computeWeightedLoss,
cosineDistance,
hingeLoss,
huberLoss,
logLoss,
meanSquaredError,
sigmoidCrossEntropy,
softmaxCrossEntropy
};
const sparse = {
sparseFillEmptyRows,
sparseReshape,
sparseSegmentMean,
sparseSegmentSum
};
// tslint:disable-next-line:variable-name
const string = {
stringNGrams,
stringSplit,
stringToHashBucketFast
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.abs = function () {
this.throwIfDisposed();
return abs(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.acos = function () {
this.throwIfDisposed();
return acos(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.acosh = function () {
this.throwIfDisposed();
return acosh(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.add = function (b) {
this.throwIfDisposed();
return add$1(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.all = function (axis, keepDims) {
this.throwIfDisposed();
return all(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.any = function (axis, keepDims) {
this.throwIfDisposed();
return any(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.argMax = function (axis) {
this.throwIfDisposed();
return argMax(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.argMin = function (axis) {
this.throwIfDisposed();
return argMin(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a size-1 `tf.Tensor` to a `tf.Scalar`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asScalar = function () {
this.throwIfDisposed();
assert(this.size === 1, () => 'The array must have only 1 element.');
return reshape(this, []);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Casts a `tf.Tensor` to a specified dtype.
*
* @param dtype Data-type to cast the tensor to.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.asType = function (dtype) {
this.throwIfDisposed();
return cast(this, dtype);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor1D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as1D = function () {
this.throwIfDisposed();
return reshape(this, [this.size]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor2D`.
*
* @param rows Number of rows in `tf.Tensor2D`.
* @param columns Number of columns in `tf.Tensor2D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as2D = function (rows, columns) {
this.throwIfDisposed();
return reshape(this, [rows, columns]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor3D`.
*
* @param rows Number of rows in `tf.Tensor3D`.
* @param columns Number of columns in `tf.Tensor3D`.
* @param depth Depth of `tf.Tensor3D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as3D = function (rows, columns, depth) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor4D`.
*
* @param rows Number of rows in `tf.Tensor4D`.
* @param columns Number of columns in `tf.Tensor4D`.
* @param depth Depth of `tf.Tensor4D`.
* @param depth2 4th dimension of `tf.Tensor4D`.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as4D = function (rows, columns, depth, depth2) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Converts a `tf.Tensor` to a `tf.Tensor5D`.
*
* @param rows Number of rows in `tf.Tensor5D`.
* @param columns Number of columns in `tf.Tensor5D`.
* @param depth Depth of `tf.Tensor5D`.
* @param depth2 4th dimension of `tf.Tensor5D`.
* @param depth3 5th dimension of 'tf.Tensor5D'
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.as5D = function (rows, columns, depth, depth2, depth3) {
this.throwIfDisposed();
return reshape(this, [rows, columns, depth, depth2, depth3]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.asin = function () {
this.throwIfDisposed();
return asin(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.asinh = function () {
this.throwIfDisposed();
return asinh(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atan = function () {
this.throwIfDisposed();
return atan(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atan2 = function (b) {
this.throwIfDisposed();
return atan2(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.atanh = function () {
this.throwIfDisposed();
return atanh(this);
};
getGlobalTensorClass().prototype.avgPool =
function (filterSize, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return avgPool(this, filterSize, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.batchToSpaceND = function (blockShape, crops) {
this.throwIfDisposed();
return batchToSpaceND(this, blockShape, crops);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.batchNorm = function (mean, variance, offset, scale, varianceEpsilon) {
this.throwIfDisposed();
return batchNorm(this, mean, variance, offset, scale, varianceEpsilon);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.broadcastTo = function (shape) {
this.throwIfDisposed();
return broadcastTo(this, shape);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cast = function (dtype) {
this.throwIfDisposed();
return cast(this, dtype);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.ceil = function () {
this.throwIfDisposed();
return ceil(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.clipByValue = function (min, max) {
this.throwIfDisposed();
return clipByValue(this, min, max);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.concat = function (x, axis) {
this.throwIfDisposed();
if (x instanceof Tensor) {
x = [x];
}
return concat([this, ...x], axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv1d = function (filter, stride, pad, dataFormat, dilation, dimRoundingMode) {
this.throwIfDisposed();
return conv1d(this, filter, stride, pad, dataFormat, dilation, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv2dTranspose =
function (filter, outputShape, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return conv2dTranspose(this, filter, outputShape, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.conv2d = function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
this.throwIfDisposed();
return conv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cos = function () {
this.throwIfDisposed();
return cos(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cosh = function () {
this.throwIfDisposed();
return cosh(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.cumsum = function (axis, exclusive, reverse) {
this.throwIfDisposed();
return cumsum(this, axis, exclusive, reverse);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.depthToSpace = function (blockSize, dataFormat) {
this.throwIfDisposed();
return depthToSpace(this, blockSize, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.depthwiseConv2d =
function (filter, strides, pad, dataFormat, dilations, dimRoundingMode) {
this.throwIfDisposed();
return depthwiseConv2d(this, filter, strides, pad, dataFormat, dilations, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.dilation2d =
function (filter, strides, pad, dilations, dataFormat) {
this.throwIfDisposed();
return dilation2d(this, filter, strides, pad, dilations, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.divNoNan = function (b) {
this.throwIfDisposed();
return divNoNan(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.div = function (b) {
this.throwIfDisposed();
return div(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.dot = function (b) {
this.throwIfDisposed();
return dot(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.elu = function () {
this.throwIfDisposed();
return elu(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.equal = function (b) {
this.throwIfDisposed();
return equal(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.erf = function () {
this.throwIfDisposed();
return erf(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.exp = function () {
this.throwIfDisposed();
return exp(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.expandDims = function (axis) {
this.throwIfDisposed();
return expandDims(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.expm1 = function () {
this.throwIfDisposed();
return expm1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.fft = function () {
this.throwIfDisposed();
return fft(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Flatten a Tensor to a 1D array.
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.flatten = function () {
this.throwIfDisposed();
return reshape(this, [this.size]);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.floor = function () {
this.throwIfDisposed();
return floor(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.floorDiv = function (b) {
this.throwIfDisposed();
return floorDiv(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.gather = function (indices, axis) {
this.throwIfDisposed();
return gather(this, indices, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.greaterEqual = function (b) {
this.throwIfDisposed();
return greaterEqual(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.greater = function (b) {
this.throwIfDisposed();
return greater(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.ifft = function () {
this.throwIfDisposed();
return ifft(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.irfft = function () {
this.throwIfDisposed();
return irfft(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isFinite = function () {
this.throwIfDisposed();
return isFinite$1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isInf = function () {
this.throwIfDisposed();
return isInf(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.isNaN = function () {
this.throwIfDisposed();
return isNaN$1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.leakyRelu = function (alpha) {
this.throwIfDisposed();
return leakyRelu(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.lessEqual = function (b) {
this.throwIfDisposed();
return lessEqual(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.less = function (b) {
this.throwIfDisposed();
return less(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.localResponseNormalization =
function (depthRadius, bias, alpha, beta) {
this.throwIfDisposed();
return localResponseNormalization(this, depthRadius, bias, alpha, beta);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSigmoid = function () {
this.throwIfDisposed();
return logSigmoid(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSoftmax = function (axis) {
this.throwIfDisposed();
return logSoftmax(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logSumExp = function (axis, keepDims) {
this.throwIfDisposed();
return logSumExp(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.log = function () {
this.throwIfDisposed();
return log$1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.log1p = function () {
this.throwIfDisposed();
return log1p(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalAnd = function (b) {
this.throwIfDisposed();
return logicalAnd(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalNot = function () {
this.throwIfDisposed();
return logicalNot(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalOr = function (b) {
this.throwIfDisposed();
return logicalOr(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.logicalXor = function (b) {
this.throwIfDisposed();
return logicalXor(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.matMul = function (b, transposeA, transposeB) {
this.throwIfDisposed();
return matMul(this, b, transposeA, transposeB);
};
getGlobalTensorClass().prototype.maxPool =
function (filterSize, strides, pad, dimRoundingMode) {
this.throwIfDisposed();
return maxPool(this, filterSize, strides, pad, dimRoundingMode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.max = function (axis, keepDims) {
this.throwIfDisposed();
return max(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.maximum = function (b) {
this.throwIfDisposed();
return maximum(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mean = function (axis, keepDims) {
this.throwIfDisposed();
return mean(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.min = function (axis, keepDims) {
this.throwIfDisposed();
return min(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.minimum = function (b) {
this.throwIfDisposed();
return minimum(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mirrorPad = function (paddings, mode) {
this.throwIfDisposed();
return mirrorPad(this, paddings, mode);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mod = function (b) {
this.throwIfDisposed();
return mod(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.mul = function (b) {
this.throwIfDisposed();
return mul(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.neg = function () {
this.throwIfDisposed();
return neg(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.norm = function (ord, axis, keepDims) {
this.throwIfDisposed();
return norm(this, ord, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.notEqual = function (b) {
this.throwIfDisposed();
return notEqual(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.oneHot = function (depth, onValue = 1, offValue = 0) {
this.throwIfDisposed();
return oneHot(this, depth, onValue, offValue);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.onesLike = function () {
this.throwIfDisposed();
return onesLike(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.pad = function (paddings, constantValue) {
this.throwIfDisposed();
return pad(this, paddings, constantValue);
};
getGlobalTensorClass().prototype.pool = function (windowShape, poolingType, padding, dilationRate, strides) {
this.throwIfDisposed();
return pool(this, windowShape, poolingType, padding, dilationRate, strides);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.pow = function (exp) {
this.throwIfDisposed();
return pow(this, exp);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.prelu = function (alpha) {
this.throwIfDisposed();
return prelu(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.prod = function (axis, keepDims) {
this.throwIfDisposed();
return prod(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.reciprocal = function () {
this.throwIfDisposed();
return reciprocal(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.relu = function () {
this.throwIfDisposed();
return relu(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.relu6 = function () {
this.throwIfDisposed();
return relu6(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Reshapes the tensor into the shape of the provided tensor.
*
* @param x The tensor of required shape.
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.reshapeAs = function (x) {
this.throwIfDisposed();
return reshape(this, x.shape);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.reshape = function (shape) {
this.throwIfDisposed();
return reshape(this, shape);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.resizeBilinear =
function (newShape2D, alignCorners, halfPixelCenters) {
this.throwIfDisposed();
return resizeBilinear(this, newShape2D, alignCorners, halfPixelCenters);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.resizeNearestNeighbor =
function (newShape2D, alignCorners, halfFloatCenters) {
this.throwIfDisposed();
return resizeNearestNeighbor(this, newShape2D, alignCorners, halfFloatCenters);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.reverse = function (axis) {
this.throwIfDisposed();
return reverse(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.rfft = function () {
this.throwIfDisposed();
return rfft(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.round = function () {
this.throwIfDisposed();
return round$1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.rsqrt = function () {
this.throwIfDisposed();
return rsqrt(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.selu = function () {
this.throwIfDisposed();
return selu(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.separableConv2d =
function (depthwiseFilter, pointwiseFilter, strides, pad, dilation, dataFormat) {
this.throwIfDisposed();
return separableConv2d(this, depthwiseFilter, pointwiseFilter, strides, pad, dilation, dataFormat);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sigmoid = function () {
this.throwIfDisposed();
return sigmoid(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sign = function () {
this.throwIfDisposed();
return sign(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sin = function () {
this.throwIfDisposed();
return sin(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sinh = function () {
this.throwIfDisposed();
return sinh(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.slice = function (begin, size) {
this.throwIfDisposed();
return slice(this, begin, size);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.softmax = function (dim) {
this.throwIfDisposed();
return softmax(this, dim);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.softplus = function () {
this.throwIfDisposed();
return softplus(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.spaceToBatchND = function (blockShape, paddings) {
this.throwIfDisposed();
return spaceToBatchND(this, blockShape, paddings);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.split = function (numOrSizeSplits, axis) {
this.throwIfDisposed();
return split(this, numOrSizeSplits, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sqrt = function () {
this.throwIfDisposed();
return sqrt(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.square = function () {
this.throwIfDisposed();
return square(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.squaredDifference = function (b) {
this.throwIfDisposed();
return squaredDifference(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.squeeze = function (axis) {
this.throwIfDisposed();
return squeeze(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.stack = function (x, axis) {
this.throwIfDisposed();
const tensorsToBeStacked = x instanceof Tensor ? [this, x] : [this, ...x];
return stack(tensorsToBeStacked, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.step = function (alpha) {
this.throwIfDisposed();
return step(this, alpha);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.stridedSlice = function (begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask) {
this.throwIfDisposed();
return stridedSlice(this, begin, end, strides, beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sub = function (b) {
this.throwIfDisposed();
return sub(this, b);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.sum = function (axis, keepDims) {
this.throwIfDisposed();
return sum$1(this, axis, keepDims);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tan = function () {
this.throwIfDisposed();
return tan(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tanh = function () {
this.throwIfDisposed();
return tanh$1(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.tile = function (reps) {
this.throwIfDisposed();
return tile(this, reps);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Casts the array to type `bool`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toBool = function () {
this.throwIfDisposed();
return cast(this, 'bool');
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Casts the array to type `float32`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toFloat = function () {
this.throwIfDisposed();
return cast(this, 'float32');
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/**
* Casts the array to type `int32`
*
* @doc {heading: 'Tensors', subheading: 'Classes'}
*/
getGlobalTensorClass().prototype.toInt = function () {
this.throwIfDisposed();
return cast(this, 'int32');
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.topk = function (k, sorted) {
this.throwIfDisposed();
return topk(this, k, sorted);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.transpose = function (perm) {
this.throwIfDisposed();
return transpose(this, perm);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.unique = function (axis) {
this.throwIfDisposed();
return unique(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.unsortedSegmentSum =
function (segmentIds, numSegments) {
this.throwIfDisposed();
return unsortedSegmentSum(this, segmentIds, numSegments);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.unstack = function (axis) {
this.throwIfDisposed();
return unstack(this, axis);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.where = function (condition, x) {
this.throwIfDisposed();
return where(condition, this, x);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
getGlobalTensorClass().prototype.zerosLike = function () {
this.throwIfDisposed();
return zerosLike(this);
};
/**
* @license
* Copyright 2020 Google LLC. 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.
* =============================================================================
*/
/** @license See the LICENSE file. */
// This code is auto-generated, do not modify this file!
var version = '3.9.0';
/**
* @license
* Copyright 2018 Google LLC. 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.
* =============================================================================
*/
var version$1 = {
'tfjs-core': tfjsCore.version_core,
'tfjs-backend-cpu': tfjsBackendCpu.version_cpu,
'tfjs-backend-webgl': tfjsBackendWebgl.version_webgl,
'tfjs-data': tfjsData.version_data,
'tfjs-layers': tfjsLayers.version_layers,
'tfjs-converter': tfjsConverter.version_converter,
'tfjs': version
};
Object.keys(tfjsCore).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsCore[k];
}
});
});
Object.keys(tfjsLayers).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsLayers[k];
}
});
});
Object.keys(tfjsConverter).forEach(function (k) {
if (k !== 'default') Object.defineProperty(exports, k, {
enumerable: true,
get: function () {
return tfjsConverter[k];
}
});
});
exports.data = tfjsData;
exports.version = version$1;
//# sourceMappingURL=tf.node.js.map
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('./reducer-0072fe54.js');
require('redux');
require('immer');
require('./Debug-c9078a39.js');
require('flatted');
require('./ai-c49ece0d.js');
require('./initialize-61b003a4.js');
var client = require('./client-f70782f6.js');
exports.Client = client.Client;
|
import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['fullheight', 'map'],
markers : [],
mapHeight: '200px',
center : [0.0, 0.0],
zoom : 3,
icon : L.icon({
iconUrl: 'assets/images/marker-icon.png',
iconRetinaUrl: 'assets/images/marker-icon@2x.png',
shadowUrl: 'assets/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [13, 40]
}),
map : null,
markersLayer : null,
onChangeMarkers : Ember.observer('markers', function(){
console.log("Chamando doutor hans chucrute");
console.log(this.get('markers'));
this.clearMarkers();
this._addMarkers(this.map, this.get('markers'));
}),
didInsertElement : function(){
this.buildMap();
},
buildMap :function(){
this.map = this._Map();
this.markersLayer = L.layerGroup();
this.markersLayer.addTo(this.map);
this._addMapLayer(this.map);
var markers = this.get('markers');
this._addMarkers(this.map, markers);
var self = this;
this.map.on('contextmenu', function onMapClick(e) {
self.map.panTo(e.latlng);
self.sendAction('contextmenu', e.latlng);
// var marker = {latitude:e.latlng[0], longitude:e.latlng[1], label: "novo"}
// self.addMarker(map, marker);
$('.marker-details-wrapper').show();
console.log("Context Menu at " + e.latlng);
});
this.map.locate({setView: true, maxZoom: 16});
},
_Map : function(){
var center = this.get('center');
var zoom = this.get('zoom');
var mapElem = this.$('.map').get(0);
var map = L.map(mapElem).setView(center, zoom);
return map;
},
_addMapLayer : function(map){
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
},
_addMarkers : function(map, markers){
if(markers){
for(var i=0; i < markers.length; ++i){
var marker = markers[i];
// L.marker([marker.latitude, marker.longitude], {icon: this.getIcon()})
// .addTo(map)
// .bindPopup(String(marker.label) + "[" + marker.latitude + ", " + marker.longitude + "]").openPopup();
this.addMarker(map, marker);
}
}
},
clearMarkers : function(){
this.markersLayer.clearLayers();
},
getIcon : function(){
return this.get('icon');
},
addMarker: function(map, marker){
var popup = new L.Popup();
popup.setContent(String(marker.label));
var mapMarker = L.marker(L.latLng(marker.latitude, marker.longitude), {icon: this.getIcon()})
//.addTo(map)
.addTo(this.markersLayer)
.bindPopup(popup, {
"offset": new L.Point(0, -32)
});
mapMarker.marker = marker;
var self = this;
mapMarker.on('click', function(e){
self.sendAction('markerclick', this.marker);
});
}
});
|
import chai, { expect } from 'chai'
import dirtyChai from 'dirty-chai'
import { PrefixOperator, InfixOperator } from './selectOps'
import { NoneSelector, AllSelector } from './selectorsBase'
chai.use(dirtyChai)
describe('PrefixOperator', () => {
const noneSelector = new NoneSelector()
const selector = new AllSelector()
selector.keyword = 'selector'
const noArgPO = new PrefixOperator()
const simplePO = new PrefixOperator(selector)
simplePO.keyword = 'simplePO'
describe('#toString()', () => {
it('constructs string for prefix operator created with no arguments', () => {
expect(noArgPO.toString()).to.equal('error none')
})
it('constructs string for higher priority prefix operator from lower priority...', () => {
const highPriorityPO = new PrefixOperator(simplePO)
highPriorityPO.priority -= 1
highPriorityPO.keyword = 'higherPO'
expect(highPriorityPO.toString()).to.equal('higherPO (simplePO selector)')
})
it('constructs string for lower priority prefix operator from higher priority...', () => {
const lowPriorityPO = new PrefixOperator(simplePO)
lowPriorityPO.priority += 1
lowPriorityPO.keyword = 'lowerPO'
expect(lowPriorityPO.toString()).to.equal('lowerPO simplePO selector')
})
})
describe('#toJSON()', () => {
it('constructs JSON for prefix operator created with no arguments', () => {
expect(noArgPO.toJSON()).to.deep.equal(['Error', noneSelector.toJSON()])
})
})
})
describe('InfixOperator', () => {
const noneSelector = new NoneSelector()
const leftSelector = new AllSelector()
leftSelector.keyword = 'lSelector'
const rightSelector = new AllSelector()
rightSelector.keyword = 'rSelector'
const noneSelectorIO = new InfixOperator()
const halfSelectorIO = new InfixOperator(leftSelector)
const selectorIO = new InfixOperator(leftSelector, rightSelector)
const highPriorityIO = new InfixOperator(leftSelector, rightSelector)
highPriorityIO.priority -= 2
highPriorityIO.keyword = '^'
const lowPriorityIO = new InfixOperator(leftSelector, rightSelector)
lowPriorityIO.priority += 2
lowPriorityIO.keyword = '+'
describe('#toString()', () => {
it('constructs string for infix operator with no arguments', () => {
expect(noneSelectorIO.toString()).to.equal('none error none')
})
it('constructs string for infix operator with one argument', () => {
expect(halfSelectorIO.toString()).to.equal('lSelector error none')
})
it('constructs string for simple infix operator', () => {
expect(selectorIO.toString()).to.equal('lSelector error rSelector')
})
it('constructs string for complex infix operator with follow priorities: middle(high, low)', () => {
const complexIO = new InfixOperator(highPriorityIO, lowPriorityIO)
complexIO.keyword = '*'
expect(complexIO.toString()).to.equal(
'lSelector ^ rSelector * (lSelector + rSelector)'
)
})
it('constructs string for complex infix operator with follow priorities: middle(low, high)', () => {
const complexIO = new InfixOperator(lowPriorityIO, highPriorityIO)
complexIO.keyword = '*'
expect(complexIO.toString()).to.equal(
'(lSelector + rSelector) * lSelector ^ rSelector'
)
})
it('constructs string for complex infix operator with follow priorities: middle(low, low)', () => {
const complexIO = new InfixOperator(lowPriorityIO, lowPriorityIO)
complexIO.keyword = '*'
expect(complexIO.toString()).to.equal(
'(lSelector + rSelector) * (lSelector + rSelector)'
)
})
it('constructs string for complex infix operator with follow priorities: middle(high, high)', () => {
const complexIO = new InfixOperator(highPriorityIO, highPriorityIO)
complexIO.keyword = '*'
expect(complexIO.toString()).to.equal(
'lSelector ^ rSelector * lSelector ^ rSelector'
)
})
})
describe('#toJSON()', () => {
it('constructs JSON for infix operator with no arguments', () => {
expect(noneSelectorIO.toJSON()).to.deep.equal([
'Error',
noneSelector.toJSON(),
noneSelector.toJSON()
])
})
it('constructs JSON for infix operator with one argument', () => {
expect(halfSelectorIO.toJSON()).to.deep.equal([
'Error',
leftSelector.toJSON(),
noneSelector.toJSON()
])
})
it('constructs JSON for simple infix operator', () => {
expect(selectorIO.toJSON()).to.deep.equal([
'Error',
leftSelector.toJSON(),
rightSelector.toJSON()
])
})
})
})
|
'use strict';
$(function() {
nodecg.listenFor('ssbmCrewUpdate', updateRosters);
nodecg.listenFor('ssbmCrewHide', hideRosters);
function updateRosters(data) {
var rosterSize = 10;
for (var i = 0; i < rosterSize; i++) {
$('#rosterleft > div:nth-child(' + (i + 1) + ')').text(data.roster1[i]);
$('#rosterright > div:nth-child(' + (i + 1) + ')').text(data.roster2[i]);
if(data.kos1[i]) {
$('#rosterleft > div:nth-child(' + (i + 1) + ')').css({
'color': '#888',
'background-color': '#ddd',
'text-decoration': 'line-through'
});
} else {
$('#rosterleft > div:nth-child(' + (i + 1) + ')').css({
'color': '#000',
'background-color': '#eee',
'text-decoration': 'none'
});
}
if(data.kos2[i]) {
$('#rosterright > div:nth-child(' + (i + 1) + ')').css({
'color': '#888',
'background-color': '#ddd',
'text-decoration': 'line-through'
});
} else {
$('#rosterright > div:nth-child(' + (i + 1) + ')').css({
'color': '#000',
'background-color': '#eee',
'text-decoration': 'none'
});
}
}
$('#crewnameleft').text(data.teamNamesStock.team1name);
$('#crewstockleft').text(data.teamNamesStock.team1stock);
$('#crewnameright').text(data.teamNamesStock.team2name);
$('#crewstockright').text(data.teamNamesStock.team2stock);
showRosters();
}
function showRosters() {
var delay = 50;
var rosterSize = 10;
$('#rosterheaderleft').animate({left: "0%"}, 500);
$('#rosterheaderright').animate({left: "0%"}, 500);
for (var i = 1; i <= rosterSize; i++) {
$('#rosterleft > div:nth-child(' + i + ')')
.delay(delay * i)
.queue(function(nxt) {
$(this).animate({left: "0%"}, 500);
nxt();
});
$('#rosterright > div:nth-child(' + i + ')')
.delay(delay * i)
.queue(function(nxt) {
$(this).animate({left: "0%"}, 500);
nxt();
});
}
//$('#rosterleft').animate({left: "0%"}, 500);
//$('#rosterright').animate({left: "0%"}, 500);
}
function hideRosters(data) {
var delay = 50;
var rosterSize = 10;
$('#rosterheaderleft').animate({left: "-275px"}, 500);
$('#rosterheaderright').animate({left: "275px"}, 500);
for (var i = 1; i <= rosterSize; i++) {
$('#rosterleft > div:nth-child(' + i + ')')
.delay(delay * i)
.queue(function(nxt) {
$(this).animate({left: "-275px"}, 500);
nxt();
});
$('#rosterright > div:nth-child(' + i + ')')
.delay(delay * i)
.queue(function(nxt) {
$(this).animate({left: "275px"}, 500);
nxt();
});
}
//$('#rosterleft').animate({left: "-275px"}, 500);
//$('#rosterright').animate({left: "275px"}, 500);
}
}) |
'use strict';
var React = require('react'),
Input = require('../common/textInput.js');
var AuthorForm = React.createClass({
propTypes: {
author: React.PropTypes.object.isRequired,
onSave: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
errors: React.PropTypes.object
},
render: function() {
return (
<form>
<h1>Manage Author</h1>
<Input
name="firstName"
label="First Name"
placeholder="First Name"
value={this.props.author.firstName}
onChange={this.props.onChange}
error={this.props.errors.firstName} />
<Input
name="lastName"
label="Last Name"
placeholder="Last Name"
value={this.props.author.lastName}
onChange={this.props.onChange}
error={this.props.errors.lastName} />
<input type="submit" value="Save" className="btn btn-default" onClick={this.props.onSave} />
</form>
);
}
});
module.exports = AuthorForm;
|
import _ from 'lodash';
export default class FormModelValidator {
// function returns index of array item that has specific key
static getArrayIndexByKey(formModelArray, key) {
formModelArray = formModelArray || [];
let index = -1;
for (let i = 0; i < formModelArray.length; i++) {
if (formModelArray[i].key === key) {
index = i;
break;
}
}
return index;
}
// function returns meta by path
static getMetaByPath(formModel, path) {
let meta = null;
if (FormModelValidator.pathIsArray(path)) {
// get info related to array of metas
let arrInfo = FormModelValidator.parsePathToArray(path);
let array = formModel[arrInfo.pathToArray]; // this array contains metas or objects with metas
array.forEach((arrayItem) => {
// skip looping if we already found meta by key
if (meta != null)
return;
// array item can be meta or object that has meta inside
if (arrayItem.key === arrInfo.itemKey) {
meta = arrInfo.arrayItemIsMeta
? arrayItem
: arrayItem[arrInfo.metaPropertyName];
}
});
// if variable meta is not actual meta, set it to undefined;
if (!FormModelValidator.objectIsMeta(meta))
meta = undefined;
} else {
meta = _.get(formModel, path);
}
return meta;
}
// function returns array of validators by path
static getValidatorsByPath(formModelValidators, path) {
let validators = null;
if (FormModelValidator.pathIsArray(path)) {
// get info related to array of metas
let arrInfo = FormModelValidator.parsePathToArray(path);
validators = formModelValidators[arrInfo.nameOfValidatorField];
} else {
validators = _.get(formModelValidators, path);
}
return validators;
}
// returns true if path points to array
static pathIsArray(path) {
return path.indexOf('[') !== -1;
}
// returns object with array paths and keys
static parsePathToArray(path) {
let result = {
itemKey: null,
pathToArray: null,
arrayItemIsMeta: false,
metaPropertyName: null,
nameOfValidatorField: null
};
let indexOfArrayOpen = path.indexOf('[');
let indexOfArrayClose = path.indexOf(']');
let arrayItemKey = path.substring(indexOfArrayOpen + 1, indexOfArrayClose);
result.itemKey = arrayItemKey;
result.pathToArray = path.substring(0, indexOfArrayOpen);
result.nameOfValidatorField = path.replace(`[${result.itemKey}]`, '[]');
result.arrayItemIsMeta = path.endsWith("]");
if (result.arrayItemIsMeta === false)
result.metaPropertyName = path.substring(path.indexOf("].") + 2);
return result;
}
// validate meta object
static isMetaValid(formModel, formModelValidators, path) {
let valid = true;
// get validator for path of the model
let validators = FormModelValidator.getValidatorsByPath(formModelValidators, path);
validators = validators || [];
// complex validation (not for specific path)
if (path === '_model') {
if (!formModel['_model']) {
formModel['_model'] = { errors: [], warnings: [], infos: [] };
} else {
formModel['_model'].errors = [];
formModel['_model'].warnings = [];
formModel['_model'].infos = [];
}
// run validator agains model value
for (let validatorItem of validators) {
let result;
try {
result = validatorItem.validator(formModel); // Note: for complex validation, there is single argument - FormModel
} catch (err) {
console.error(`\nError while running validator for '_model'`);
console.error(err);
}
if (result === false) {
let message = null;
if (typeof (validatorItem.message) === 'string') {
message = validatorItem.message;
} else if (typeof (validatorItem.message) === 'function') {
message = validatorItem.message(meta.value, formModel);
}
else {
console.error('Validator\'s message property is not string or function.');
}
// add message to corresponding array
if (message != null) {
if (validatorItem.type === 'error') {
formModel['_model'].errors.push(message);
valid = false;
}
else if (validatorItem.type === 'info')
formModel['_model'].infos.push(message);
else if (validatorItem.type === 'warning')
formModel['_model'].warnings.push(message);
else {
valid = false;
formModel['_model'].errors.push(message); // if type is not set, treat is as error
console.warn(`Validator for '_model' is missing type property.`);
}
}
}
// if validator returned something other than boolean, log it to console
if (typeof (result) !== 'boolean') {
console.error(`Validator returned result of type ${typeof (result)} for '_model'`);
}
}
} else {
let meta = FormModelValidator.getMetaByPath(formModel, path);
// get form model value for path
if (!meta) {
console.error(`FormModelValidator.isMetaValid: cannot find path of '${path}' in form model.
Check form model and form model validators for matching keys`);
return true; // just mark meta as valid
}
// clear previous errors
meta.errors = [];
meta.warnings = [];
meta.infos = [];
// run validator agains model value
for (let validatorItem of validators) {
// For errors array, we allow only 1 error to be present
if (validatorItem.type === 'error' || typeof (validatorItem.type) === 'undefined') {
if (meta.errors.length != 0)
continue;
}
// execute validator and get result (should be boolean)
let result;
try {
result = validatorItem.validator(meta.value, formModel); // Note: for each validator function, we pass second parameter that is FormModel
}
catch (err) {
console.error(`\nError while running validator for meta '${meta.name}'`);
console.error(err);
}
if (result === false) {
let message = null;
if (typeof (validatorItem.message) === 'string') {
message = validatorItem.message;
} else if (typeof (validatorItem.message) === 'function') {
message = validatorItem.message(meta.value, formModel);
}
else {
console.error('Validator\'s message property is not string or function.');
}
// WARNING: meta is invalid if type of failed validator is type of 'error'
// add message to corresponding array
if (message != null) {
if (validatorItem.type === 'error') {
meta.errors.push(message);
valid = false;
}
else if (validatorItem.type === 'info')
meta.infos.push(message);
else if (validatorItem.type === 'warning')
meta.warnings.push(message);
else {
valid = false;
meta.errors.push(message); // if type is not set, treat is as error
console.warn(`Validator for ${meta.name} is missing type property.`);
}
}
}
// if validator returned something other than boolean, log it to console
if (typeof (result) !== 'boolean') {
console.error(`Validator returned result of type ${typeof (result)} for meta '${meta.name}'`);
}
}
}
return valid;
}
// function loop all paths and run validators for each path. Return type is boolean
static isModelValid(formModel, formModelValidators, stopOnFirstError) {
stopOnFirstError = stopOnFirstError || false; // if provided TRUE, then validation stops on first error
let valid = true;
// get paths of all paths that needed to be validated
let validatorPaths = [];
_.forOwn(formModelValidators, (fieldValue, fieldName, obj) => {
if (typeof fieldValue !== 'function') {
validatorPaths.push(fieldName);
}
});
// now loop every path and validate value at path
for (let pathIndex = 0; pathIndex < validatorPaths.length; pathIndex++) {
if (valid === false && stopOnFirstError === true)
break;
let path = validatorPaths[pathIndex];
if (FormModelValidator.pathIsArray(path)) {
// path points to array. It means we need to loop array and validate each item of array
let arrayOfValidators = formModelValidators[path];
let arrInfo = FormModelValidator.parsePathToArray(path);
// get array from form model. Each array item is meta or object with metas
let formModelArray = formModel[arrInfo.pathToArray];
// now loop items inside array and run validator against each meta
formModelArray.forEach((arrayItem) => {
let meta = arrInfo.arrayItemIsMeta
? arrayItem
: arrayItem[arrInfo.metaPropertyName];
let result = FormModelValidator.isMetaValid(formModel, formModelValidators, meta.name);
if (!result) {
valid = false;
}
});
} else {
let result = FormModelValidator.isMetaValid(formModel, formModelValidators, path);
if (!result) {
valid = false;
if (stopOnFirstError === true)
break;
}
}
}
return valid;
}
// function checks is passed object has shape of metadata
static objectIsMeta(obj) {
if (obj) {
return obj.hasOwnProperty('value') && !_.isObject(obj.value) && !_.isArray(obj.value);
}
return false;
}
// path can contains "." Function split path by dot and creates nested objects (after last dot is property name)
// example: contactInfo.address.city will result into.
// { contactInfo: {
// address: { }
// }
// Warning: "city" will not be added to "address" object
static getOrCreateNestedObjects(json, path) {
var parts = path.split('.');
let nestedObject = json;
for (let partIndex = 0; partIndex < parts.length - 1; partIndex++) {
let part = parts[partIndex];
if (nestedObject.hasOwnProperty(part) === false)
nestedObject[part] = {};
nestedObject = nestedObject[part];
}
return nestedObject;
}
// path can contains "." Function split path by dot and creates nested array
// example: contactInfo.labels will result into.
// { contactInfo: {
// labels: []
// }
static getOrCreateNestedArray(json, path) {
var parts = path.split('.');
let nestedObject = json;
// loop path and build or get deepest object
for (let partIndex = 0; partIndex < parts.length; partIndex++) {
let part = parts[partIndex];
// if it is the last part in path, then create empty array
if (partIndex === parts.length - 1) {
if (typeof (nestedObject[part]) === 'undefined')
nestedObject[part] = [];
} else {
if (nestedObject.hasOwnProperty(part) === false)
nestedObject[part] = {};
}
nestedObject = nestedObject[part];
}
return nestedObject;
}
// function accepts form model and return plain json object (json that we send to API)
static getJSON(formModel, formModelValidators) {
// Make a copy of formModel
let formModelCopy = _.cloneDeep(formModel);
// we always need to delete formModel['_model'] property. It is used only to display errors on web page
delete formModelCopy['_model'];
let result = {};
_.forOwn(formModelCopy, (metaOrArray, path) => {
if (_.isArray(metaOrArray)) {
//let arrayForJson = FormModelValidator.getOrCreateNestedArray(result, path);
_.set(result, path, []);
let arrayForJson = _.get(result, path);
metaOrArray.forEach((arrayItem) => {
// if formModelValidators contains function that creates json, use it
if (formModelValidators && typeof formModelValidators[`${path}[].getJSON`] === 'function') {
let customJson = formModelValidators[`${path}[].getJSON`](arrayItem, formModelCopy);
if (typeof(customJson) !== 'undefined' && customJson !== null) {
arrayForJson.push(customJson);
}
} else {
// if each array item is meta, then add value of that meta to array
if (arrayItem.key && FormModelValidator.objectIsMeta(arrayItem)) {
arrayForJson.push({ key: arrayItem.key, value: arrayItem.value });
}
else {
let objectWithManyValues = {
key: arrayItem.key,
value: {}
};
// array item is not meta, now loop properties of object to find all metas
_.forOwn(arrayItem, (arrayItemPathValue, arrayItemPath) => {
if (FormModelValidator.objectIsMeta(arrayItemPathValue)) {
objectWithManyValues.value[arrayItemPath] = arrayItemPathValue.value;
}
});
arrayForJson.push(objectWithManyValues);
}
}
});
}
else if (FormModelValidator.objectIsMeta(metaOrArray)) {
if (formModelValidators && typeof formModelValidators[`${path}.getJSON`] === 'function') {
let customValue = formModelValidators[`${path}.getJSON`](metaOrArray, formModelCopy);
if (typeof(customValue) !== 'undefined' && customValue !== null) {
_.set(result, path, customValue);
}
} else {
_.set(result, path, metaOrArray.value);
}
}
});
return result;
}
// function accepts form model and return plain json object with just errors/warnings/infos
static getErrors(formModel) {
let errors = {};
_.forOwn(formModel, (metaOrArray, path) => {
if (_.isArray(metaOrArray)) {
// this is array, loop array to get errors from array items
metaOrArray.forEach((arrayItem) => {
if (arrayItem.key && FormModelValidator.objectIsMeta(arrayItem)) {
// array item is object that contains single meta
let errorObjKeyName = `${path}[${arrayItem.key}]`; // key name of error object
if (arrayItem.errors && arrayItem.errors.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].errors = arrayItem.errors;
}
if (arrayItem.warnings && arrayItem.warnings.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].warnings = arrayItem.warnings;
}
if (arrayItem.infos && arrayItem.infos.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].infos = arrayItem.infos;
}
} else {
// array item is object that contains multiple meta, loop object proeprties and get errors from each meta
_.forOwn(arrayItem, (arrayItemObjectPropValue, arrayItemObjectPropName) => {
const errorObjKeyName = `${path}[${arrayItem.key}].${arrayItemObjectPropName}`;
if (FormModelValidator.objectIsMeta(arrayItemObjectPropValue)) {
if (arrayItemObjectPropValue.errors && arrayItemObjectPropValue.errors.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].errors = arrayItemObjectPropValue.errors;
}
if (arrayItemObjectPropValue.warnings && arrayItemObjectPropValue.warnings.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].warnings = arrayItemObjectPropValue.warnings;
}
if (arrayItemObjectPropValue.infos && arrayItemObjectPropValue.infos.length > 0) {
if (!errors[errorObjKeyName]) { errors[errorObjKeyName] = {}; }
errors[errorObjKeyName].infos = arrayItemObjectPropValue.infos;
}
}
});
}
});
} else if (FormModelValidator.objectIsMeta(metaOrArray) || path === "_model") {
if (metaOrArray.errors && metaOrArray.errors.length > 0) {
if (!errors[path]) { errors[path] = {}; }
errors[path].errors = metaOrArray.errors;
}
if (metaOrArray.warnings && metaOrArray.warnings.length > 0) {
if (!errors[path]) { errors[path] = {}; }
errors[path].warnings = metaOrArray.warnings;
}
if (metaOrArray.infos && metaOrArray.infos.length > 0) {
if (!errors[path]) { errors[path] = {}; }
errors[path].infos = metaOrArray.infos;
}
}
});
return errors;
}
// function puts errors in form-model (when we get model validation on server).
static replaceErrors(formModel, errors) {
_.forOwn(errors, (obj, path) => {
let meta = null;
if (path === '_model') {
meta = FormModelValidator.getMetaByPath(formModel, path);
if (!meta) {
meta = {};
formModel['_model'] = meta;
}
} else {
meta = FormModelValidator.getMetaByPath(formModel, path);
}
if (meta) {
meta.errors = [];
meta.errors = obj.errors;
meta.warnings = obj.warnings;
meta.infos = obj.infos;
}
});
return formModel;
}
// function returns true if form model has errors (validators will not be run agains form model paths)
static hasExistingErrors(formModel) {
let hasErrors = false;
_.forOwn(formModel, (metaOrArray, path) => {
if (hasErrors === true) {
return hasErrors;
}
if (_.isArray(metaOrArray)) {
// this is array, loop array to get errors from array items
metaOrArray.forEach((arrayItem) => {
if (FormModelValidator.objectIsMeta(arrayItem)) {
// array item is meta, get errors form that meta
if (arrayItem.errors && arrayItem.errors.length > 0) {
hasErrors = true;
}
} else {
// array item is object that contains meta, loop object proeprties and get errors from each meta
_.forOwn(arrayItem, (arrayItemObjectPropValue, arrayItemObjectPropName) => {
if (FormModelValidator.objectIsMeta(arrayItemObjectPropValue)) {
// array item is meta, get errors form that meta
if (arrayItemObjectPropValue.errors && arrayItemObjectPropValue.errors.length > 0) {
hasErrors = true;
}
}
});
}
});
} else if (FormModelValidator.objectIsMeta(metaOrArray) || path === "_model") {
if (metaOrArray.errors && metaOrArray.errors.length > 0) {
hasErrors = true;
}
}
});
return hasErrors;
}
} |
F(function(){
F("documents", F.Component.extend({
getBtn: function(){ return this.$container.find(".btn-load_more"); },
init: function(name, $container) {
var self = this;
self._super(name, $container);
self.subscribe(F.TOPIC.ENV_CHANGED, function(topic, data){
if (data.conn || data.db || data.col) self.load();
});
self.subscribe(F.TOPIC.DATA_TABLE.BODY_UPDATED, function(topic, data){
if (data.all_loaded) self.getBtn().hide();
else self.getBtn().show();
});
},
afterRender: function(callback){
var self = this;
self.getBtn().click(function(){
self.publish(F.TOPIC.DATA_TABLE.LOAD_MORE);
self.getBtn().hide();
});
callback();
}
}));
F("table_part", F.Component.extend({
showColumn: function(colName) {
this.$("." + MONGRES.col2Class(colName)).removeClass("hide");
},
hideColumn: function(colName) {
this.$("." + MONGRES.col2Class(colName)).addClass("hide");
},
}));
});
|
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./src/app.js'
],
output: {
path : path.join(__dirname, 'public'),
pathinfo : true,
filename : 'bundle.js',
publicPath : '/public/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
],
resolve: {
extensions: ['', '.json', '.js', '.jsx']
},
module: {
loaders: [
{
test : /\.jsx?$/,
loader : 'babel',
exclude : /node_modules/,
include : path.join(__dirname, 'src')
},
{
test : /\.scss?$/,
loader : 'style!css!sass',
include : path.join(__dirname, 'sass')
},
{
test : /\.(png|jpg)$/,
loader : 'file'
},
{
test : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader : 'file'
},
{
include : /\.json$/,
loaders : ["json-loader"]
}
]
}
}
|
define(["./when-54c2dc71","./Check-6c0211bc","./Math-fc8cecf5","./Cartesian2-a8ce88a9","./Transforms-9ac5213c","./RuntimeError-2109023a","./WebGLConstants-76bb35d1","./ComponentDatatype-6d99a1ee","./GeometryAttribute-ded8350c","./GeometryAttributes-4fcfcf40","./Plane-29afec1f","./VertexFormat-7572c785","./FrustumGeometry-a91b289d"],function(r,e,t,c,a,n,u,o,m,f,s,d,i){"use strict";return function(e,t){return r.defined(t)&&(e=i.FrustumGeometry.unpack(e,t)),i.FrustumGeometry.createGeometry(e)}}); |
var Readable = require('stream').Readable;
function getMockCommentsStream(comments) {
var stream = new Readable({ objectMode: true });
var index = 0;
stream._read = function () {
var comment;
if (index < comments.length) {
comment = comments[index];
// if comment has a type that contains "error" then treat it as an error
if (comment.type && /error/i.test(comment.type)) {
stream.emit('error', comment);
}
else {
stream.push(comment);
}
index++;
}
else {
stream.push(null);
}
};
return stream;
}
module.exports = getMockCommentsStream;
|
let hot_Scene_Map=()=>{
let Scene_Map_prototype_update=Scene_Map.prototype.update
let Scene_Map_createAllWindows=Scene_Map.prototype.createAllWindows
Object.assign(Scene_Map.prototype,{
disFromCharacter(character_1,character_2){
return Math.abs(this.deltaX(character_1._realX, character_2._realX)) + Math.abs(this.deltaY(character_1._realY, character_2._realY))
//实际上没有this,因为Scene_Map不是$gameMap
},
//改写了原生的窗口加载,实现加载的血条,现在可以去掉
createAllWindows(){
Scene_Map_createAllWindows.call(this)
console.log('加载Winbar')
if(true){
//因为影响到了保存,所以把血条系统关掉,似乎是在遍历的时候遍历不到什么所以没法保存?不知道
this.addWindow(new Window_Bar($gamePlayer))
for(let _e of $gameMap.events()){
this.addWindow(new Window_Bar(_e))
}}
},
//鼠标触发事件
_startEventByTouch(x,y,triggers,normal){
if (!$gameMap.isEventRunning()) {
$gameMap.eventsXy(x, y).forEach(function(event) {
//把事件触发event._trigger和传入的事件做比较
console.log(event)
//不知道Priority是什么,什么东西的优先级?
//当事件可穿透的时候,可能是优先级相关的
//if (event._trigger==2 && event.isNormalPriority() === normal) {
//if (event._trigger==2 ) {//隔空直接触发
//x或y在线上触发后才触发,角色会先走动到线上,等再次点击才触发
//或许需要其他方式,比如在move到点的时候触发
//trigger2时直接触发,0时面向触发
if (event._trigger==0 && ($gamePlayer._x==x||$gamePlayer._y==y)) {
event.start()
}else if(event._trigger==2){
event.start()
}
})
}
},
//地图检索触控事件
processMapTouch(){
let triggers_默认事件=2 //鼠标默认点击触发“事件接触”事件
//0时需要坐标一致才鼠标触发
if (TouchInput.isTriggered() || this._touchCount > 0) {
if (TouchInput.isPressed()) {
if (this._touchCount === 0 || this._touchCount >= 15) {
var x = $gameMap.canvasToMapX(TouchInput.x)
var y = $gameMap.canvasToMapY(TouchInput.y)
//引用了我的方法
//先不开启,换成在Game_player类中开启,结合移动
//-----------------------------------------------------------------!!!!!!!!!
//this._startEventByTouch(x, y, triggers_默认事件, true)
$gameTemp.setDestination(x, y)
}
this._touchCount++
} else {
this._touchCount = 0
}
}
},
update(){
//Scene_Map_prototype_update.call(this)
//响应按钮跳跃 问题是还没把视角移动,并且边界判定
//console.log(1)
if(Input.isPressed('space')){
$gamePlayer.jumpStraight()
//响应按钮删掉所有事件
//console.log($gameMap._events)
/*
for(let _e of $gameMap._events){
if(!!_e){
_e.erase()//是自己函数名写错了,erase没有下划线
//_e._erased = true//有问题,根本这类的属性都没有了
//_e.refresh()//由于事件列表的第一个是空函数,所以不行 //直接 _erase的方法不见了,只能用次一级的方法
}
}
*/
//$gameMap._events[2].clearPageSettings()
//压根不生效,可能和场景自己的update冲突或者在this的获得有问题,因为总是undefined
//$gameMap._events.splice(2,1)
//$gameMap._events[2].erase()
//console.log($gameMap)
/*
for(let _e of $gameMap._events){
if(typeof(_e._erase)=="undefined"){
_e._erase()
}
}
*/
/*
for(let i=0;i<=$gameMap._events.length;i++){
console.log(i)
$gameMap._events[i]._erase()
}
*/
}
if(Input.isPressed('shift')){
if(!$gamePlayer.isMoving()){
//$gamePlayer.moveTowardCharacter()
$gamePlayer.setMoveSpeed(6)
$gamePlayer.moveStraight($gamePlayer._direction)
/*
switch($gamePlayer._direction){
case 8:
$gamePlayer.jump(0,-2)
break
case 2:
$gamePlayer.jump(0,2)
break
case 4:
$gamePlayer.jump(-2,0)
break
case 6:
$gamePlayer.jump(2,0)
break
}
*/
}
//响应按钮删掉所有事件
//console.log($gameMap._events)
/*
for(let _e of $gameMap._events){
if(!!_e){
_e.erase()//是自己函数名写错了,erase没有下划线
//_e._erased = true//有问题,根本这类的属性都没有了
//_e.refresh()//由于事件列表的第一个是空函数,所以不行 //直接 _erase的方法不见了,只能用次一级的方法
}
}
*/
//$gameMap._events[2].clearPageSettings()
//压根不生效,可能和场景自己的update冲突或者在this的获得有问题,因为总是undefined
//$gameMap._events.splice(2,1)
//$gameMap._events[2].erase()
//console.log($gameMap)
/*
for(let _e of $gameMap._events){
if(typeof(_e._erase)=="undefined"){
_e._erase()
}
}
*/
/*
for(let i=0;i<=$gameMap._events.length;i++){
console.log(i)
$gameMap._events[i]._erase()
}
*/
}
if(Input.isPressed('control')){
SceneManager._scene._spriteset._tilemap.children.splice(8,1)
//console.log($gameMap.disFromCharacter($gamePlayer,$gameMap.events()[0]))
if(!$gamePlayer.isMoving()){
//$gamePlayer.moveTowardCharacter()
//$gamePlayer.turnTowardCharacter()
//$gameMap._event[1]
}
}
if(Input.isPressed('f')){
console.log(1)
let animation=$dataAnimations[3]
var name1 = animation.animation1Name
var name2 = animation.animation2Name
var hue1 = animation.animation1Hue
var hue2 = animation.animation2Hue
ImageManager.requestAnimation(name1, hue1)
ImageManager.requestAnimation(name2, hue2)
}
if(Input.isPressed('h')){
$gamePlayer.skillCharacter()
}
Scene_Map_prototype_update.call(this)
},
})
}
module.exports=hot_Scene_Map
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _three = require('three');
var THREE = _interopRequireWildcard(_three);
var _ReactPropTypes = require('react/lib/ReactPropTypes');
var _ReactPropTypes2 = _interopRequireDefault(_ReactPropTypes);
var _MaterialDescriptorBase = require('./MaterialDescriptorBase');
var _MaterialDescriptorBase2 = _interopRequireDefault(_MaterialDescriptorBase);
var _propTypeInstanceOf = require('../../utils/propTypeInstanceOf');
var _propTypeInstanceOf2 = _interopRequireDefault(_propTypeInstanceOf);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MeshStandardMaterialDescriptor = function (_MaterialDescriptorBa) {
_inherits(MeshStandardMaterialDescriptor, _MaterialDescriptorBa);
function MeshStandardMaterialDescriptor(react3RendererInstance) {
_classCallCheck(this, MeshStandardMaterialDescriptor);
var _this = _possibleConstructorReturn(this, (MeshStandardMaterialDescriptor.__proto__ || Object.getPrototypeOf(MeshStandardMaterialDescriptor)).call(this, react3RendererInstance));
_this.hasColor();
_this.hasColor('emissive', 0x000000);
_this.hasWireframe();
['roughness', 'metalness'].forEach(function (propName) {
_this.hasProp(propName, {
type: _ReactPropTypes2.default.number,
simple: true,
default: 0.5
});
});
['lightMapIntensity', 'aoMapIntensity', 'emissiveIntensity', 'bumpScale', 'displacementScale'].forEach(function (propName) {
_this.hasProp(propName, {
type: _ReactPropTypes2.default.number,
update: function update(threeObject, propValue) {
threeObject[propName] = propValue;
threeObject.needsUpdate = true;
},
default: 1
});
});
['displacementBias'].forEach(function (propName) {
_this.hasProp(propName, {
type: _ReactPropTypes2.default.number,
update: function update(threeObject, propValue) {
threeObject[propName] = propValue;
threeObject.needsUpdate = true;
},
default: 0
});
});
['refractionRatio'].forEach(function (propName) {
_this.hasProp(propName, {
type: _ReactPropTypes2.default.number,
update: function update(threeObject, propValue) {
threeObject[propName] = propValue;
threeObject.needsUpdate = true;
},
default: 0.98
});
});
_this.hasProp('normalScale', {
type: (0, _propTypeInstanceOf2.default)(THREE.Vector2),
update: function update(threeObject, normalScale) {
threeObject.normalScale.copy(normalScale);
threeObject.needsUpdate = true;
},
default: new THREE.Vector2(1, 1)
});
_this.hasProp('shading', {
type: _ReactPropTypes2.default.oneOf([THREE.FlatShading, THREE.SmoothShading]),
update: function update(threeObject, shading) {
threeObject.shading = shading;
threeObject.needsUpdate = true;
},
default: THREE.SmoothShading
});
['skinning', 'morphTargets', 'morphNormals'].forEach(function (propName) {
_this.hasProp(propName, {
type: _ReactPropTypes2.default.bool,
update: function update(threeObject, propValue) {
threeObject[propName] = propValue;
threeObject.needsUpdate = true;
},
default: false
});
});
return _this;
}
_createClass(MeshStandardMaterialDescriptor, [{
key: 'getMaterialDescription',
value: function getMaterialDescription(props) {
var materialDescription = _get(MeshStandardMaterialDescriptor.prototype.__proto__ || Object.getPrototypeOf(MeshStandardMaterialDescriptor.prototype), 'getMaterialDescription', this).call(this, props);
['roughness', 'metalness', 'lightMapIntensity', 'aoMapIntensity', 'emissiveIntensity', 'bumpScale', 'displacementScale', 'displacementBias', 'refractionRatio', 'normalScale', 'shading', 'skinning', 'morphTargets', 'morphNormals'].forEach(function (propName) {
if (props.hasOwnProperty(propName)) {
materialDescription[propName] = props[propName];
}
});
return materialDescription;
}
}, {
key: 'construct',
value: function construct(props) {
var materialDescription = this.getMaterialDescription(props);
return new THREE.MeshStandardMaterial(materialDescription);
}
}]);
return MeshStandardMaterialDescriptor;
}(_MaterialDescriptorBase2.default);
module.exports = MeshStandardMaterialDescriptor; |
/*!
* Native JavaScript for Bootstrap - Carousel v4.1.0alpha4 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2022 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Carousel = factory());
})(this, (function () { 'use strict';
/**
* A global namespace for `mouseenter` event.
* @type {string}
*/
const mouseenterEvent = 'mouseenter';
/**
* A global namespace for `mouseleave` event.
* @type {string}
*/
const mouseleaveEvent = 'mouseleave';
/**
* A global namespace for `click` event.
* @type {string}
*/
const mouseclickEvent = 'click';
/**
* A global namespace for `keydown` event.
* @type {string}
*/
const keydownEvent = 'keydown';
/**
* A global namespace for `touchmove` event.
* @type {string}
*/
const touchmoveEvent = 'touchmove';
/**
* A global namespace for `touchend` event.
* @type {string}
*/
const touchendEvent = 'touchend';
/**
* A global namespace for `touchstart` event.
* @type {string}
*/
const touchstartEvent = 'touchstart';
/**
* A global namespace for `ArrowLeft` key.
* @type {string} e.which = 37 equivalent
*/
const keyArrowLeft = 'ArrowLeft';
/**
* A global namespace for `ArrowRight` key.
* @type {string} e.which = 39 equivalent
*/
const keyArrowRight = 'ArrowRight';
/**
* Returns the `Window` object of a target node.
* @see https://github.com/floating-ui/floating-ui
*
* @param {(Node | HTMLElement | Element | Window)=} node target node
* @returns {globalThis}
*/
function getWindow(node) {
if (node == null) {
return window;
}
if (!(node instanceof Window)) {
const { ownerDocument } = node;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
// @ts-ignore
return node;
}
/**
* Returns the `document` or the `#document` element.
* @see https://github.com/floating-ui/floating-ui
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {Document}
*/
function getDocument(node) {
if (node instanceof HTMLElement) return node.ownerDocument;
if (node instanceof Window) return node.document;
return window.document;
}
/**
* A global namespace for 'transitionDuration' string.
* @type {string}
*/
const transitionDuration = 'transitionDuration';
/**
* A global namespace for:
* * `transitionProperty` string for Firefox,
* * `transition` property for all other browsers.
*
* @type {string}
*/
const transitionProperty = 'transitionProperty';
/**
* Shortcut for `window.getComputedStyle(element).propertyName`
* static method.
*
* * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
* throws a `ReferenceError`.
*
* @param {HTMLElement | Element} element target
* @param {string} property the css property
* @return {string} the css property value
*/
function getElementStyle(element, property) {
const computedStyle = getComputedStyle(element);
// @ts-ignore -- must use camelcase strings,
// or non-camelcase strings with `getPropertyValue`
return property in computedStyle ? computedStyle[property] : '';
}
/**
* Utility to get the computed `transitionDuration`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDuration(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const durationValue = getElementStyle(element, transitionDuration);
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Returns the bounding client rect of a target `HTMLElement`.
*
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element event.target
* @param {boolean=} includeScale when *true*, the target scale is also computed
* @returns {SHORTER.BoundingClientRect} the bounding client rect object
*/
function getBoundingClientRect(element, includeScale) {
const {
width, height, top, right, bottom, left,
} = element.getBoundingClientRect();
let scaleX = 1;
let scaleY = 1;
if (includeScale && element instanceof HTMLElement) {
const { offsetWidth, offsetHeight } = element;
scaleX = offsetWidth > 0 ? Math.round(width) / offsetWidth || 1 : 1;
scaleY = offsetHeight > 0 ? Math.round(height) / offsetHeight || 1 : 1;
}
return {
width: width / scaleX,
height: height / scaleY,
top: top / scaleY,
right: right / scaleX,
bottom: bottom / scaleY,
left: left / scaleX,
x: left / scaleX,
y: top / scaleY,
};
}
/**
* Returns the `document.documentElement` or the `<html>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLHtmlElement}
*/
function getDocumentElement(node) {
return getDocument(node).documentElement;
}
/**
* Utility to determine if an `HTMLElement`
* is partially visible in viewport.
*
* @param {HTMLElement | Element} element target
* @return {boolean} the query result
*/
const isElementInScrollRange = (element) => {
const { top, bottom } = getBoundingClientRect(element);
const { clientHeight } = getDocumentElement(element);
// checks bottom && top
return top <= clientHeight && bottom >= 0;
};
/**
* Checks if a page is Right To Left.
* @param {(HTMLElement | Element)=} node the target
* @returns {boolean} the query result
*/
const isRTL = (node) => getDocumentElement(node).dir === 'rtl';
/**
* Shortcut for `HTMLElement.closest` method which also works
* with children of `ShadowRoot`. The order of the parameters
* is intentional since they're both required.
*
* @see https://stackoverflow.com/q/54520554/803358
*
* @param {HTMLElement | Element} element Element to look into
* @param {string} selector the selector name
* @return {(HTMLElement | Element)?} the query result
*/
function closest(element, selector) {
return element ? (element.closest(selector)
// @ts-ignore -- break out of `ShadowRoot`
|| closest(element.getRootNode().host, selector)) : null;
}
/**
* A global array of possible `ParentNode`.
*/
const parentNodes = [Document, Node, Element, HTMLElement];
/**
* A global array with `Element` | `HTMLElement`.
*/
const elementNodes = [Element, HTMLElement];
/**
* Utility to check if target is typeof `HTMLElement`, `Element`, `Node`
* or find one that matches a selector.
*
* @param {HTMLElement | Element | string} selector the input selector or target element
* @param {(HTMLElement | Element | Node | Document)=} parent optional node to look into
* @return {(HTMLElement | Element)?} the `HTMLElement` or `querySelector` result
*/
function querySelector(selector, parent) {
const selectorIsString = typeof selector === 'string';
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
if (!selectorIsString && elementNodes.some((x) => selector instanceof x)) {
return selector;
}
// @ts-ignore -- `ShadowRoot` is also a node
return selectorIsString ? lookUp.querySelector(selector) : null;
}
/**
* A shortcut for `(document|Element).querySelectorAll`.
*
* @param {string} selector the input selector
* @param {(HTMLElement | Element | Document | Node)=} parent optional node to look into
* @return {NodeListOf<HTMLElement | Element>} the query result
*/
function querySelectorAll(selector, parent) {
const lookUp = parent && parentNodes
.some((x) => parent instanceof x) ? parent : getDocument();
// @ts-ignore -- `ShadowRoot` is also a node
return lookUp.querySelectorAll(selector);
}
/**
* Shortcut for `HTMLElement.getElementsByClassName` method. Some `Node` elements
* like `ShadowRoot` do not support `getElementsByClassName`.
*
* @param {string} selector the class name
* @param {(HTMLElement | Element | Document)=} parent optional Element to look into
* @return {HTMLCollectionOf<HTMLElement | Element>} the 'HTMLCollection'
*/
function getElementsByClassName(selector, parent) {
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
return lookUp.getElementsByClassName(selector);
}
/**
* Shortcut for `HTMLElement.getAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const getAttribute = (element, attribute) => element.getAttribute(attribute);
/** @type {Map<HTMLElement | Element, any>} */
const TimeCache = new Map();
/**
* An interface for one or more `TimerHandler`s per `Element`.
* @see https://github.com/thednp/navbar.js/
*/
const Timer = {
/**
* Sets a new timeout timer for an element, or element -> key association.
* @param {HTMLElement | Element | string} target target element
* @param {ReturnType<TimerHandler>} callback the callback
* @param {number} delay the execution delay
* @param {string=} key a unique
*/
set: (target, callback, delay, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
if (!TimeCache.has(element)) {
TimeCache.set(element, new Map());
}
const keyTimers = TimeCache.get(element);
keyTimers.set(key, setTimeout(callback, delay));
} else {
TimeCache.set(element, setTimeout(callback, delay));
}
},
/**
* Returns the timer associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique
* @returns {number?} the timer
*/
get: (target, key) => {
const element = querySelector(target);
if (!element) return null;
const keyTimers = TimeCache.get(element);
if (key && key.length && keyTimers && keyTimers.get) {
return keyTimers.get(key) || null;
}
return keyTimers || null;
},
/**
* Clears the element's timer.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique key
*/
clear: (target, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
const keyTimers = TimeCache.get(element);
if (keyTimers && keyTimers.get) {
clearTimeout(keyTimers.get(key));
keyTimers.delete(key);
if (keyTimers.size === 0) {
TimeCache.delete(element);
}
}
} else {
clearTimeout(TimeCache.get(element));
TimeCache.delete(element);
}
},
};
/**
* Utility to force re-paint of an `HTMLElement` target.
*
* @param {HTMLElement | Element} element is the target
* @return {number} the `Element.offsetHeight` value
*/
// @ts-ignore
const reflow = (element) => element.offsetHeight;
/**
* A global namespace for most scroll event listeners.
* @type {Partial<AddEventListenerOptions>}
*/
const passiveHandler = { passive: true };
/**
* A global namespace for 'transitionend' string.
* @type {string}
*/
const transitionEndEvent = 'transitionend';
/**
* A global namespace for 'transitionDelay' string.
* @type {string}
*/
const transitionDelay = 'transitionDelay';
/**
* Utility to get the computed `transitionDelay`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDelay(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const delayValue = getElementStyle(element, transitionDelay);
const delayScale = delayValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(delayValue) * delayScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Add eventListener to an `Element` | `HTMLElement` | `Document` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function on$1(element, eventName, handler, options) {
const ops = options || false;
element.addEventListener(eventName, handler, ops);
}
/**
* Remove eventListener from an `Element` | `HTMLElement` | `Document` | `Window` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function off$1(element, eventName, handler, options) {
const ops = options || false;
element.removeEventListener(eventName, handler, ops);
}
/**
* Utility to make sure callbacks are consistently
* called when transition ends.
*
* @param {HTMLElement | Element} element target
* @param {EventListener} handler `transitionend` callback
*/
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
const delay = getElementTransitionDelay(element);
if (duration) {
/**
* Wrap the handler in on -> off callback
* @param {TransitionEvent} e Event object
*/
const transitionEndWrapper = (e) => {
if (e.target === element) {
handler.apply(element, [e]);
off$1(element, transitionEndEvent, transitionEndWrapper);
called = 1;
}
};
on$1(element, transitionEndEvent, transitionEndWrapper);
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + delay + 17);
} else {
handler.apply(element, [endEvent]);
}
}
/**
* Shortcut for `Object.assign()` static method.
* @param {Record<string, any>} obj a target object
* @param {Record<string, any>} source a source object
*/
const ObjectAssign = (obj, source) => Object.assign(obj, source);
/**
* Shortcut for the `Element.dispatchEvent(Event)` method.
*
* @param {HTMLElement | Element} element is the target
* @param {Event} event is the `Event` object
*/
const dispatchEvent = (element, event) => element.dispatchEvent(event);
/** @type {Map<string, Map<HTMLElement | Element, Record<string, any>>>} */
const componentData = new Map();
/**
* An interface for web components background data.
* @see https://github.com/thednp/bootstrap.native/blob/master/src/components/base-component.js
*/
const Data = {
/**
* Sets web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @param {Record<string, any>} instance the component instance
*/
set: (target, component, instance) => {
const element = querySelector(target);
if (!element) return;
if (!componentData.has(component)) {
componentData.set(component, new Map());
}
const instanceMap = componentData.get(component);
// @ts-ignore - not undefined, but defined right above
instanceMap.set(element, instance);
},
/**
* Returns all instances for specified component.
* @param {string} component the component's name or a unique key
* @returns {Map<HTMLElement | Element, Record<string, any>>?} all the component instances
*/
getAllFor: (component) => {
const instanceMap = componentData.get(component);
return instanceMap || null;
},
/**
* Returns the instance associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @returns {Record<string, any>?} the instance
*/
get: (target, component) => {
const element = querySelector(target);
const allForC = Data.getAllFor(component);
const instance = element && allForC && allForC.get(element);
return instance || null;
},
/**
* Removes web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
*/
remove: (target, component) => {
const element = querySelector(target);
const instanceMap = componentData.get(component);
if (!instanceMap || !element) return;
instanceMap.delete(element);
if (instanceMap.size === 0) {
componentData.delete(component);
}
},
};
/**
* An alias for `Data.get()`.
* @type {SHORTER.getInstance<any>}
*/
const getInstance = (target, component) => Data.get(target, component);
/**
* Returns a namespaced `CustomEvent` specific to each component.
* @param {string} EventType Event.type
* @param {Record<string, any>=} config Event.options | Event.properties
* @returns {SHORTER.OriginalEvent} a new namespaced event
*/
function OriginalEvent(EventType, config) {
const OriginalCustomEvent = new CustomEvent(EventType, {
cancelable: true, bubbles: true,
});
if (config instanceof Object) {
ObjectAssign(OriginalCustomEvent, config);
}
return OriginalCustomEvent;
}
/**
* Add class to `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to add
*/
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
/**
* Check class in `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to check
* @return {boolean}
*/
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
/**
* Remove class from `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to remove
*/
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
/** @type {Record<string, any>} */
const EventRegistry = {};
/**
* The global event listener.
*
* @this {Element | HTMLElement | Window | Document}
* @param {Event} e
* @returns {void}
*/
function globalListener(e) {
const that = this;
const { type } = e;
const oneEvMap = EventRegistry[type] ? [...EventRegistry[type]] : [];
oneEvMap.forEach((elementsMap) => {
const [element, listenersMap] = elementsMap;
[...listenersMap].forEach((listenerMap) => {
if (element === that) {
const [listener, options] = listenerMap;
listener.apply(element, [e]);
if (options && options.once) {
removeListener(element, type, listener, options);
}
}
});
});
}
/**
* Register a new listener with its options and attach the `globalListener`
* to the target if this is the first listener.
*
* @param {Element | HTMLElement | Window | Document} element
* @param {string} eventType
* @param {EventListenerObject['handleEvent']} listener
* @param {AddEventListenerOptions=} options
*/
const addListener = (element, eventType, listener, options) => {
// get element listeners first
if (!EventRegistry[eventType]) {
EventRegistry[eventType] = new Map();
}
const oneEventMap = EventRegistry[eventType];
if (!oneEventMap.has(element)) {
oneEventMap.set(element, new Map());
}
const oneElementMap = oneEventMap.get(element);
// get listeners size
const { size } = oneElementMap;
// register listener with its options
if (oneElementMap) {
oneElementMap.set(listener, options);
}
// add listener last
if (!size) {
element.addEventListener(eventType, globalListener, options);
}
};
/**
* Remove a listener from registry and detach the `globalListener`
* if no listeners are found in the registry.
*
* @param {Element | HTMLElement | Window | Document} element
* @param {string} eventType
* @param {EventListenerObject['handleEvent']} listener
* @param {AddEventListenerOptions=} options
*/
const removeListener = (element, eventType, listener, options) => {
// get listener first
const oneEventMap = EventRegistry[eventType];
const oneElementMap = oneEventMap && oneEventMap.get(element);
const savedOptions = oneElementMap && oneElementMap.get(listener);
// also recover initial options
const { options: eventOptions } = savedOptions !== undefined
? savedOptions
: { options };
// unsubscribe second, remove from registry
if (oneElementMap && oneElementMap.has(listener)) oneElementMap.delete(listener);
if (oneEventMap && (!oneElementMap || !oneElementMap.size)) oneEventMap.delete(element);
if (!oneEventMap || !oneEventMap.size) delete EventRegistry[eventType];
// remove listener last
if (!oneElementMap || !oneElementMap.size) {
element.removeEventListener(eventType, globalListener, eventOptions);
}
};
/**
* Advanced event listener based on subscribe / publish pattern.
* @see https://www.patterns.dev/posts/classic-design-patterns/#observerpatternjavascript
* @see https://gist.github.com/shystruk/d16c0ee7ac7d194da9644e5d740c8338#file-subpub-js
* @see https://hackernoon.com/do-you-still-register-window-event-listeners-in-each-component-react-in-example-31a4b1f6f1c8
*/
const EventListener = {
on: addListener,
off: removeListener,
globalListener,
registry: EventRegistry,
};
/**
* Global namespace for most components active class.
*/
const activeClass = 'active';
/**
* Global namespace for most components `target` option.
*/
const dataBsTarget = 'data-bs-target';
/** @type {string} */
const carouselString = 'carousel';
/** @type {string} */
const carouselComponent = 'Carousel';
/**
* Global namespace for most components `parent` option.
*/
const dataBsParent = 'data-bs-parent';
/**
* Global namespace for most components `container` option.
*/
const dataBsContainer = 'data-bs-container';
/**
* Returns the `Element` that THIS one targets
* via `data-bs-target`, `href`, `data-bs-parent` or `data-bs-container`.
*
* @param {HTMLElement | Element} element the target element
* @returns {(HTMLElement | Element)?} the query result
*/
function getTargetElement(element) {
const targetAttr = [dataBsTarget, dataBsParent, dataBsContainer, 'href'];
const doc = getDocument(element);
return targetAttr.map((att) => {
const attValue = getAttribute(element, att);
if (attValue) {
return att === dataBsParent ? closest(element, attValue) : querySelector(attValue, doc);
}
return null;
}).filter((x) => x)[0];
}
/**
* The raw value or a given component option.
*
* @typedef {string | HTMLElement | Function | number | boolean | null} niceValue
*/
/**
* Utility to normalize component options
*
* @param {any} value the input value
* @return {niceValue} the normalized value
*/
function normalizeValue(value) {
if (value === 'true') { // boolean
return true;
}
if (value === 'false') { // boolean
return false;
}
if (!Number.isNaN(+value)) { // number
return +value;
}
if (value === '' || value === 'null') { // null
return null;
}
// string / function / HTMLElement / object
return value;
}
/**
* Shortcut for `Object.keys()` static method.
* @param {Record<string, any>} obj a target object
* @returns {string[]}
*/
const ObjectKeys = (obj) => Object.keys(obj);
/**
* Shortcut for `String.toLowerCase()`.
*
* @param {string} source input string
* @returns {string} lowercase output string
*/
const toLowerCase = (source) => source.toLowerCase();
/**
* Utility to normalize component options.
*
* @param {HTMLElement | Element} element target
* @param {Record<string, any>} defaultOps component default options
* @param {Record<string, any>} inputOps component instance options
* @param {string=} ns component namespace
* @return {Record<string, any>} normalized component options object
*/
function normalizeOptions(element, defaultOps, inputOps, ns) {
// @ts-ignore -- our targets are always `HTMLElement`
const data = { ...element.dataset };
/** @type {Record<string, any>} */
const normalOps = {};
/** @type {Record<string, any>} */
const dataOps = {};
const title = 'title';
ObjectKeys(data).forEach((k) => {
const key = ns && k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => toLowerCase(match))
: k;
dataOps[key] = normalizeValue(data[k]);
});
ObjectKeys(inputOps).forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
ObjectKeys(defaultOps).forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = k === title
? getAttribute(element, title)
: defaultOps[k];
}
});
return normalOps;
}
var version = "4.1.0alpha4";
const Version = version;
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
/** Returns a new `BaseComponent` instance. */
class BaseComponent {
/**
* @param {HTMLElement | Element | string} target `Element` or selector string
* @param {BSN.ComponentOptions=} config component instance options
*/
constructor(target, config) {
const self = this;
const element = querySelector(target);
if (!element) {
throw Error(`${self.name} Error: "${target}" is not a valid selector.`);
}
/** @static @type {BSN.ComponentOptions} */
self.options = {};
const prevInstance = Data.get(element, self.name);
if (prevInstance) prevInstance.dispose();
/** @type {HTMLElement | Element} */
self.element = element;
if (self.defaults && Object.keys(self.defaults).length) {
self.options = normalizeOptions(element, self.defaults, (config || {}), 'bs');
}
Data.set(element, self.name, self);
}
/* eslint-disable */
/** @static */
get version() { return Version; }
/* eslint-enable */
/** @static */
get name() { return this.constructor.name; }
/** @static */
// @ts-ignore
get defaults() { return this.constructor.defaults; }
/**
* Removes component from target element;
*/
dispose() {
const self = this;
Data.remove(self.element, self.name);
// @ts-ignore
ObjectKeys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Carousel
----------------------------------------------- */
// CAROUSEL PRIVATE GC
// ===================
const carouselSelector = `[data-bs-ride="${carouselString}"]`;
const carouselItem = `${carouselString}-item`;
const dataBsSlideTo = 'data-bs-slide-to';
const dataBsSlide = 'data-bs-slide';
const { on, off } = EventListener;
const pausedClass = 'paused';
const carouselDefaults = {
pause: 'hover',
keyboard: false,
touch: true,
interval: 5000,
};
/**
* Static method which returns an existing `Carousel` instance associated
* to a target `Element`.
*
* @type {BSN.GetInstance<Carousel>}
*/
const getCarouselInstance = (element) => getInstance(element, carouselComponent);
/**
* A `Carousel` initialization callback.
* @type {BSN.InitCallback<Carousel>}
*/
const carouselInitCallback = (element) => new Carousel(element);
let startX = 0;
let currentX = 0;
let endX = 0;
// CAROUSEL CUSTOM EVENTS
// ======================
const carouselSlideEvent = OriginalEvent(`slide.bs.${carouselString}`);
const carouselSlidEvent = OriginalEvent(`slid.bs.${carouselString}`);
// CAROUSEL EVENT HANDLERS
// =======================
/**
* The `transitionend` event listener of the `Carousel`.
* @param {Carousel} self the `Carousel` instance
*/
function carouselTransitionEndHandler(self) {
const {
index, direction, element, slides, options,
} = self;
// discontinue disposed instances
if (self.isAnimating && getCarouselInstance(element)) {
const activeItem = getActiveIndex(self);
const orientation = direction === 'left' ? 'next' : 'prev';
const directionClass = direction === 'left' ? 'start' : 'end';
addClass(slides[index], activeClass);
removeClass(slides[index], `${carouselItem}-${orientation}`);
removeClass(slides[index], `${carouselItem}-${directionClass}`);
removeClass(slides[activeItem], activeClass);
removeClass(slides[activeItem], `${carouselItem}-${directionClass}`);
dispatchEvent(element, carouselSlidEvent);
Timer.clear(element, dataBsSlide);
// check for element, might have been disposed
if (!getDocument(element).hidden && options.interval
&& !self.isPaused) {
self.cycle();
}
}
}
/**
* Handles the `mouseenter` / `touchstart` events when *options.pause*
* is set to `hover`.
*
* @this {HTMLElement | Element}
*/
function carouselPauseHandler() {
const element = this;
const self = getCarouselInstance(element);
if (self && !self.isPaused && !Timer.get(element, pausedClass)) {
addClass(element, pausedClass);
}
}
/**
* Handles the `mouseleave` / `touchend` events when *options.pause*
* is set to `hover`.
*
* @this {HTMLElement | Element}
*/
function carouselResumeHandler() {
const element = this;
const self = getCarouselInstance(element);
if (self && self.isPaused && !Timer.get(element, pausedClass)) {
self.cycle();
}
}
/**
* Handles the `click` event for the `Carousel` indicators.
*
* @this {HTMLElement}
* @param {MouseEvent} e the `Event` object
*/
function carouselIndicatorHandler(e) {
e.preventDefault();
const indicator = this;
const element = closest(indicator, carouselSelector) || getTargetElement(indicator);
if (!element) return;
const self = getCarouselInstance(element);
if (!self || self.isAnimating) return;
// @ts-ignore
const newIndex = +getAttribute(indicator, dataBsSlideTo);
if (indicator && !hasClass(indicator, activeClass) // event target is not active
&& !Number.isNaN(newIndex)) { // AND has the specific attribute
self.to(newIndex); // do the slide
}
}
/**
* Handles the `click` event for the `Carousel` arrows.
*
* @this {HTMLElement}
* @param {MouseEvent} e the `Event` object
*/
function carouselControlsHandler(e) {
e.preventDefault();
const control = this;
const element = closest(control, carouselSelector) || getTargetElement(control);
const self = element && getCarouselInstance(element);
if (!self || self.isAnimating) return;
const orientation = getAttribute(control, dataBsSlide);
if (orientation === 'next') {
self.next();
} else if (orientation === 'prev') {
self.prev();
}
}
/**
* Handles the keyboard `keydown` event for the visible `Carousel` elements.
*
* @param {KeyboardEvent} e the `Event` object
*/
function carouselKeyHandler({ code }) {
const [element] = [...querySelectorAll(carouselSelector)]
.filter((x) => isElementInScrollRange(x));
const self = getCarouselInstance(element);
if (!self) return;
const RTL = isRTL();
const arrowKeyNext = !RTL ? keyArrowRight : keyArrowLeft;
const arrowKeyPrev = !RTL ? keyArrowLeft : keyArrowRight;
if (code === arrowKeyPrev) self.prev();
else if (code === arrowKeyNext) self.next();
}
// CAROUSEL TOUCH HANDLERS
// =======================
/**
* Handles the `touchdown` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e the `Event` object
*/
function carouselTouchDownHandler(e) {
const element = this;
const self = getCarouselInstance(element);
if (!self || self.isTouch) { return; }
startX = e.changedTouches[0].pageX;
// @ts-ignore
if (element.contains(e.target)) {
self.isTouch = true;
toggleCarouselTouchHandlers(self, true);
}
}
/**
* Handles the `touchmove` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e
*/
function carouselTouchMoveHandler(e) {
const { changedTouches, type } = e;
const self = getCarouselInstance(this);
if (!self || !self.isTouch) { return; }
currentX = changedTouches[0].pageX;
// cancel touch if more than one changedTouches detected
if (type === touchmoveEvent && changedTouches.length > 1) {
e.preventDefault();
}
}
/**
* Handles the `touchend` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e
*/
function carouselTouchEndHandler(e) {
const element = this;
const self = getCarouselInstance(element);
if (!self || !self.isTouch) { return; }
endX = currentX || e.changedTouches[0].pageX;
if (self.isTouch) {
// the event target is outside the carousel OR carousel doens't include the related target
// @ts-ignore
if ((!element.contains(e.target) || !element.contains(e.relatedTarget))
&& Math.abs(startX - endX) < 75) { // AND swipe distance is less than 75px
// when the above conditions are satisfied, no need to continue
return;
} // OR determine next index to slide to
if (currentX < startX) {
self.index += 1;
} else if (currentX > startX) {
self.index -= 1;
}
self.isTouch = false;
self.to(self.index); // do the slide
toggleCarouselTouchHandlers(self); // remove touch events handlers
}
}
// CAROUSEL PRIVATE METHODS
// ========================
/**
* Sets active indicator for the `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {number} pageIndex the index of the new active indicator
*/
function activateCarouselIndicator(self, pageIndex) {
const { indicators } = self;
[...indicators].forEach((x) => removeClass(x, activeClass));
if (self.indicators[pageIndex]) addClass(indicators[pageIndex], activeClass);
}
/**
* Toggles the touch event listeners for a given `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {boolean=} add when `TRUE` event listeners are added
*/
function toggleCarouselTouchHandlers(self, add) {
const { element } = self;
const action = add ? on : off;
action(element, touchmoveEvent, carouselTouchMoveHandler, passiveHandler);
action(element, touchendEvent, carouselTouchEndHandler, passiveHandler);
}
/**
* Toggles all event listeners for a given `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {boolean=} add when `TRUE` event listeners are added
*/
function toggleCarouselHandlers(self, add) {
const {
element, options, slides, controls, indicators,
} = self;
const {
touch, pause, interval, keyboard,
} = options;
const action = add ? on : off;
if (pause && interval) {
action(element, mouseenterEvent, carouselPauseHandler);
action(element, mouseleaveEvent, carouselResumeHandler);
action(element, touchstartEvent, carouselPauseHandler, passiveHandler);
action(element, touchendEvent, carouselResumeHandler, passiveHandler);
}
if (touch && slides.length > 1) {
action(element, touchstartEvent, carouselTouchDownHandler, passiveHandler);
}
if (controls.length) {
controls.forEach((arrow) => {
if (arrow) action(arrow, mouseclickEvent, carouselControlsHandler);
});
}
if (indicators.length) {
indicators.forEach((indicator) => {
action(indicator, mouseclickEvent, carouselIndicatorHandler);
});
}
// @ts-ignore
if (keyboard) action(getWindow(element), keydownEvent, carouselKeyHandler);
}
/**
* Returns the index of the current active item.
* @param {Carousel} self the `Carousel` instance
* @returns {number} the query result
*/
function getActiveIndex(self) {
const { slides, element } = self;
const activeItem = querySelector(`.${carouselItem}.${activeClass}`, element);
// @ts-ignore
return [...slides].indexOf(activeItem);
}
// CAROUSEL DEFINITION
// ===================
/** Creates a new `Carousel` instance. */
class Carousel extends BaseComponent {
/**
* @param {HTMLElement | Element | string} target mostly a `.carousel` element
* @param {BSN.Options.Carousel=} config instance options
*/
constructor(target, config) {
super(target, config);
// bind
const self = this;
// additional properties
/** @type {string} */
self.direction = isRTL() ? 'right' : 'left';
/** @type {number} */
self.index = 0;
/** @type {boolean} */
self.isTouch = false;
// initialization element
const { element } = self;
// carousel elements
// a LIVE collection is prefferable
self.slides = getElementsByClassName(carouselItem, element);
const { slides } = self;
// invalidate when not enough items
// no need to go further
if (slides.length < 2) { return; }
self.controls = [
...querySelectorAll(`[${dataBsSlide}]`, element),
...querySelectorAll(`[${dataBsSlide}][${dataBsTarget}="#${element.id}"]`),
];
/** @type {(HTMLElement | Element)?} */
self.indicator = querySelector(`.${carouselString}-indicators`, element);
// a LIVE collection is prefferable
/** @type {(HTMLElement | Element)[]} */
self.indicators = [
...(self.indicator ? querySelectorAll(`[${dataBsSlideTo}]`, self.indicator) : []),
...querySelectorAll(`[${dataBsSlideTo}][${dataBsTarget}="#${element.id}"]`),
];
// set JavaScript and DATA API options
const { options } = self;
// don't use TRUE as interval, it's actually 0, use the default 5000ms better
self.options.interval = options.interval === true
? carouselDefaults.interval
: options.interval;
// set first slide active if none
if (getActiveIndex(self) < 0) {
if (slides.length) addClass(slides[0], activeClass);
if (self.indicators.length) activateCarouselIndicator(self, 0);
}
// attach event handlers
toggleCarouselHandlers(self, true);
// start to cycle if interval is set
if (options.interval) self.cycle();
}
/* eslint-disable */
/**
* Returns component name string.
* @readonly @static
*/
get name() { return carouselComponent; }
/**
* Returns component default options.
* @readonly @static
*/
get defaults() { return carouselDefaults; }
/* eslint-enable */
/**
* Check if instance is paused.
* @returns {boolean}
*/
get isPaused() {
return hasClass(this.element, pausedClass);
}
/**
* Check if instance is animating.
* @returns {boolean}
*/
get isAnimating() {
return querySelector(`.${carouselItem}-next,.${carouselItem}-prev`, this.element) !== null;
}
// CAROUSEL PUBLIC METHODS
// =======================
/** Slide automatically through items. */
cycle() {
const self = this;
const { element, options, isPaused } = self;
Timer.clear(element, carouselString);
if (isPaused) {
Timer.clear(element, pausedClass);
removeClass(element, pausedClass);
}
Timer.set(element, () => {
if (!self.isPaused && isElementInScrollRange(element)) {
self.index += 1;
self.to(self.index);
}
}, options.interval, carouselString);
}
/** Pause the automatic cycle. */
pause() {
const self = this;
const { element, options } = self;
if (!self.isPaused && options.interval) {
addClass(element, pausedClass);
Timer.set(element, () => {}, 1, pausedClass);
}
}
/** Slide to the next item. */
next() {
const self = this;
if (!self.isAnimating) { self.index += 1; self.to(self.index); }
}
/** Slide to the previous item. */
prev() {
const self = this;
if (!self.isAnimating) { self.index -= 1; self.to(self.index); }
}
/**
* Jump to the item with the `idx` index.
* @param {number} idx the index of the item to jump to
*/
to(idx) {
const self = this;
const {
element, slides, options,
} = self;
const activeItem = getActiveIndex(self);
const RTL = isRTL();
let next = idx;
// when controled via methods, make sure to check again
// first return if we're on the same item #227
if (self.isAnimating || activeItem === next) return;
// determine transition direction
if ((activeItem < next) || (activeItem === 0 && next === slides.length - 1)) {
self.direction = RTL ? 'right' : 'left'; // next
} else if ((activeItem > next) || (activeItem === slides.length - 1 && next === 0)) {
self.direction = RTL ? 'left' : 'right'; // prev
}
const { direction } = self;
// find the right next index
if (next < 0) { next = slides.length - 1; } else if (next >= slides.length) { next = 0; }
// orientation, class name, eventProperties
const orientation = direction === 'left' ? 'next' : 'prev';
const directionClass = direction === 'left' ? 'start' : 'end';
const eventProperties = {
relatedTarget: slides[next],
from: activeItem,
to: next,
direction,
};
// update event properties
ObjectAssign(carouselSlideEvent, eventProperties);
ObjectAssign(carouselSlidEvent, eventProperties);
// discontinue when prevented
dispatchEvent(element, carouselSlideEvent);
if (carouselSlideEvent.defaultPrevented) return;
// update index
self.index = next;
activateCarouselIndicator(self, next);
if (getElementTransitionDuration(slides[next]) && hasClass(element, 'slide')) {
Timer.set(element, () => {
addClass(slides[next], `${carouselItem}-${orientation}`);
reflow(slides[next]);
addClass(slides[next], `${carouselItem}-${directionClass}`);
addClass(slides[activeItem], `${carouselItem}-${directionClass}`);
emulateTransitionEnd(slides[next], () => carouselTransitionEndHandler(self));
}, 17, dataBsSlide);
} else {
addClass(slides[next], activeClass);
removeClass(slides[activeItem], activeClass);
Timer.set(element, () => {
Timer.clear(element, dataBsSlide);
// check for element, might have been disposed
if (element && options.interval && !self.isPaused) {
self.cycle();
}
dispatchEvent(element, carouselSlidEvent);
}, 17, dataBsSlide);
}
}
/** Remove `Carousel` component from target. */
dispose() {
const self = this;
const { slides } = self;
const itemClasses = ['start', 'end', 'prev', 'next'];
[...slides].forEach((slide, idx) => {
if (hasClass(slide, activeClass)) activateCarouselIndicator(self, idx);
itemClasses.forEach((c) => removeClass(slide, `${carouselItem}-${c}`));
});
toggleCarouselHandlers(self);
super.dispose();
}
}
ObjectAssign(Carousel, {
selector: carouselSelector,
init: carouselInitCallback,
getInstance: getCarouselInstance,
});
return Carousel;
}));
|
/*
Highcharts JS v9.0.1 (2021-02-15)
Timeline series
(c) 2010-2021 Highsoft AS
Author: Daniel Studencki
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/timeline",["highcharts"],function(k){a(k);a.Highcharts=k;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function k(a,f,k,r){a.hasOwnProperty(f)||(a[f]=r.apply(null,k))}a=a?a._modules:{};k(a,"Series/Timeline/TimelinePoint.js",[a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,f){var k=this&&this.__extends||
function(){var a=function(c,d){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,d){a.__proto__=d}||function(a,d){for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c])};return a(c,d)};return function(c,d){function v(){this.constructor=c}a(c,d);c.prototype=null===d?Object.create(d):(v.prototype=d.prototype,new v)}}(),r=a.seriesTypes.pie.prototype.pointClass,y=f.defined,h=f.isNumber,z=f.merge,q=f.objectEach,w=f.pick;return function(a){function c(){var d=null!==a&&a.apply(this,arguments)||
this;d.options=void 0;d.series=void 0;return d}k(c,a);c.prototype.alignConnector=function(){var a=this.series,c=this.connector,m=this.dataLabel,h=this.dataLabel.options=z(a.options.dataLabels,this.options.dataLabels),g=this.series.chart,p=c.getBBox(),e=p.x+m.translateX;p=p.y+m.translateY;g.inverted?p-=m.options.connectorWidth/2:e+=m.options.connectorWidth/2;g=g.isInsidePlot(e,p);c[g?"animate":"attr"]({d:this.getConnectorPath()});a.chart.styledMode||c.attr({stroke:h.connectorColor||this.color,"stroke-width":h.connectorWidth,
opacity:m[y(m.newOpacity)?"newOpacity":"opacity"]})};c.prototype.drawConnector=function(){var a=this.series;this.connector||(this.connector=a.chart.renderer.path(this.getConnectorPath()).attr({zIndex:-1}).add(this.dataLabel));this.series.chart.isInsidePlot(this.dataLabel.x,this.dataLabel.y)&&this.alignConnector()};c.prototype.getConnectorPath=function(){var a=this.series.chart,c=this.series.xAxis.len,m=a.inverted,f=m?"x2":"y2",g=this.dataLabel,p=g.targetPosition,e={x1:this.plotX,y1:this.plotY,x2:this.plotX,
y2:h(p.y)?p.y:g.y},b=(g.alignAttr||g)[f[0]]<this.series.yAxis.len/2;m&&(e={x1:this.plotY,y1:c-this.plotX,x2:p.x||g.x,y2:c-this.plotX});b&&(e[f]+=g[m?"width":"height"]);q(e,function(b,a){e[a]-=(g.alignAttr||g)[a[0]]});return a.renderer.crispLine([["M",e.x1,e.y1],["L",e.x2,e.y2]],g.options.connectorWidth)};c.prototype.init=function(){var c=a.prototype.init.apply(this,arguments);c.name=w(c.name,"Event");c.y=1;return c};c.prototype.isValid=function(){return null!==this.options.y};c.prototype.setState=
function(){var c=a.prototype.setState;this.isNull||c.apply(this,arguments)};c.prototype.setVisible=function(a,c){var d=this.series;c=w(c,d.options.ignoreHiddenPoint);r.prototype.setVisible.call(this,a,!1);d.processData();c&&d.chart.redraw()};return c}(a.series.prototype.pointClass)});k(a,"Series/Timeline/TimelineSeries.js",[a["Mixins/LegendSymbol.js"],a["Core/Color/Palette.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Renderer/SVG/SVGElement.js"],a["Series/Timeline/TimelinePoint.js"],a["Core/Utilities.js"]],
function(a,f,k,r,y,h){var z=this&&this.__extends||function(){var a=function(c,b){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,a){b.__proto__=a}||function(b,a){for(var l in a)a.hasOwnProperty(l)&&(b[l]=a[l])};return a(c,b)};return function(c,b){function l(){this.constructor=c}a(c,b);c.prototype=null===b?Object.create(b):(l.prototype=b.prototype,new l)}}(),q=k.seriesTypes,w=q.column,A=q.line,c=h.addEvent,d=h.arrayMax,v=h.arrayMin,m=h.defined;q=h.extend;var x=h.merge,g=h.pick;
h=function(a){function e(){var b=null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;b.userOptions=void 0;b.visibilityMap=void 0;return b}z(e,a);e.prototype.alignDataLabel=function(b,l,c,e){var n=this.chart.inverted,d=this.visibilityMap.filter(function(a){return a}),t=this.visiblePointsCount,u=d.indexOf(b);d=this.options.dataLabels;var g=b.userDLOptions||{};u=d.alternate?u&&u!==t-1?2:1.5:1;t=Math.floor(this.xAxis.len/t);var f=l.padding;if(b.visible){var h=Math.abs(g.x||
b.options.dataLabels.x);n?(n=2*(h-f)-b.itemHeight/2,n={width:n+"px",textOverflow:l.width/n*l.height/2>t*u?"ellipsis":"none"}):n={width:(g.width||d.width||t*u-2*f)+"px"};l.css(n);this.chart.styledMode||l.shadow(d.shadow)}a.prototype.alignDataLabel.apply(this,arguments)};e.prototype.bindAxes=function(){var b=this;a.prototype.bindAxes.call(b);["xAxis","yAxis"].forEach(function(a){"xAxis"!==a||b[a].userOptions.type||(b[a].categories=b[a].hasNames=!0)})};e.prototype.distributeDL=function(){var a=this,
c=a.options.dataLabels,n,d,e={},g=1,f=c.distance;a.points.forEach(function(b){b.visible&&!b.isNull&&(n=b.options,d=b.options.dataLabels,a.hasRendered||(b.userDLOptions=x({},d)),e[a.chart.inverted?"x":"y"]=c.alternate&&g%2?-f:f,n.dataLabels=x(e,b.userDLOptions),g++)})};e.prototype.generatePoints=function(){var b=this;a.prototype.generatePoints.apply(b);b.points.forEach(function(a,c){a.applyOptions({x:b.xData[c]},b.xData[c])})};e.prototype.getVisibilityMap=function(){return(this.data.length?this.data:
this.userOptions.data).map(function(a){return a&&!1!==a.visible&&!a.isNull?a:!1})};e.prototype.getXExtremes=function(a){var b=this;a=a.filter(function(a,c){return b.points[c].isValid()&&b.points[c].visible});return{min:v(a),max:d(a)}};e.prototype.init=function(){var b=this;a.prototype.init.apply(b,arguments);b.eventsToUnbind.push(c(b,"afterTranslate",function(){var a,c=Number.MAX_VALUE;b.points.forEach(function(b){b.isInside=b.isInside&&b.visible;b.visible&&!b.isNull&&(m(a)&&(c=Math.min(c,Math.abs(b.plotX-
a))),a=b.plotX)});b.closestPointRangePx=c}));b.eventsToUnbind.push(c(b,"drawDataLabels",function(){b.distributeDL()}));b.eventsToUnbind.push(c(b,"afterDrawDataLabels",function(){var a;b.points.forEach(function(b){if(a=b.dataLabel)return a.animate=function(a){this.targetPosition&&(this.targetPosition=a);return r.prototype.animate.apply(this,arguments)},a.targetPosition||(a.targetPosition={}),b.drawConnector()})}));b.eventsToUnbind.push(c(b.chart,"afterHideOverlappingLabel",function(){b.points.forEach(function(a){a.connector&&
a.dataLabel&&a.dataLabel.oldOpacity!==a.dataLabel.newOpacity&&a.alignConnector()})}))};e.prototype.markerAttribs=function(b,c){var d=this.options.marker,e=b.marker||{},f=e.symbol||d.symbol,h=g(e.width,d.width,this.closestPointRangePx),l=g(e.height,d.height),k=0;if(this.xAxis.dateTime)return a.prototype.markerAttribs.call(this,b,c);c&&(d=d.states[c]||{},c=e.states&&e.states[c]||{},k=g(c.radius,d.radius,k+(d.radiusPlus||0)));b.hasImage=f&&0===f.indexOf("url");return{x:Math.floor(b.plotX)-h/2-k/2,y:b.plotY-
l/2-k/2,width:h+k,height:l+k}};e.prototype.processData=function(){var b=0,c;this.visibilityMap=this.getVisibilityMap();this.visibilityMap.forEach(function(a){a&&b++});this.visiblePointsCount=b;for(c=0;c<this.xData.length;c++)this.yData[c]=1;a.prototype.processData.call(this,arguments)};e.defaultOptions=x(A.defaultOptions,{colorByPoint:!0,stickyTracking:!1,ignoreHiddenPoint:!0,legendType:"point",lineWidth:4,tooltip:{headerFormat:'<span style="color:{point.color}">\u25cf</span> <span style="font-size: 10px"> {point.key}</span><br/>',
pointFormat:"{point.description}"},states:{hover:{lineWidthPlus:0}},dataLabels:{enabled:!0,allowOverlap:!0,alternate:!0,backgroundColor:f.backgroundColor,borderWidth:1,borderColor:f.neutralColor40,borderRadius:3,color:f.neutralColor80,connectorWidth:1,distance:100,formatter:function(){var a=this.series.chart.styledMode?"<span>\u25cf </span>":'<span style="color:'+this.point.color+'">\u25cf </span>';return a+='<span class="highcharts-strong">'+(this.key||"")+"</span><br/>"+(this.point.label||"")},
style:{textOutline:"none",fontWeight:"normal",fontSize:"12px"},shadow:!1,verticalAlign:"middle"},marker:{enabledThreshold:0,symbol:"square",radius:6,lineWidth:2,height:15},showInLegend:!1,colorKey:"x"});return e}(A);q(h.prototype,{drawLegendSymbol:a.drawRectangle,drawTracker:w.prototype.drawTracker,pointClass:y,trackerGroups:["markerGroup","dataLabelsGroup"]});k.registerSeriesType("timeline",h);"";"";return h});k(a,"masters/modules/timeline.src.js",[],function(){})});
//# sourceMappingURL=timeline.js.map |
/*!
* jQuery QueryBuilder 2.6.0
* Locale: Azerbaijan (az)
* Author: Megaplan, mborisv <bm@megaplan.ru>
* Licensed under MIT (https://opensource.org/licenses/MIT)
*/
(function(root, factory) {
if (typeof define == 'function' && define.amd) {
define(['jquery', 'query-builder'], factory);
}
else {
factory(root.jQuery);
}
}(this, function($) {
"use strict";
var QueryBuilder = $.fn.queryBuilder;
QueryBuilder.regional['az'] = {
"__locale": "Azerbaijan (az)",
"__author": "Megaplan, mborisv <bm@megaplan.ru>",
"add_rule": "Əlavə etmək",
"add_group": "Qrup əlavə etmək",
"delete_rule": "Silmək",
"delete_group": "Silmək",
"conditions": {
"AND": "VƏ",
"OR": "VƏ YA"
},
"operators": {
"equal": "bərabərdir",
"not_equal": "bərabər deyil",
"in": "qeyd edilmişlərdən",
"not_in": "qeyd olunmamışlardan",
"less": "daha az",
"less_or_equal": "daha az və ya bərabər",
"greater": "daha çox",
"greater_or_equal": "daha çox və ya bərabər",
"between": "arasında",
"begins_with": "başlayır",
"not_begins_with": "başlamır",
"contains": "ibarətdir",
"not_contains": "yoxdur",
"ends_with": "başa çatır",
"not_ends_with": "başa çatmır",
"is_empty": "boş sətir",
"is_not_empty": "boş olmayan sətir",
"is_null": "boşdur",
"is_not_null": "boş deyil"
},
"errors": {
"no_filter": "Filterlər seçilməyib",
"empty_group": "Qrup boşdur",
"radio_empty": "Məna seçilməyib",
"checkbox_empty": "Məna seçilməyib",
"select_empty": "Məna seçilməyib",
"string_empty": "Doldurulmayıb",
"string_exceed_min_length": "{0} daha çox simvol olmalıdır",
"string_exceed_max_length": "{0} daha az simvol olmalıdır",
"string_invalid_format": "Yanlış format ({0})",
"number_nan": "Rəqəm deyil",
"number_not_integer": "Rəqəm deyil",
"number_not_double": "Rəqəm deyil",
"number_exceed_min": "{0} daha çox olmalıdır",
"number_exceed_max": "{0} daha az olmalıdır",
"number_wrong_step": "{0} bölünən olmalıdır",
"datetime_empty": "Doldurulmayıb",
"datetime_invalid": "Yanlış tarix formatı ({0})",
"datetime_exceed_min": "{0} sonra olmalıdır",
"datetime_exceed_max": "{0} əvvəl olmalıdır",
"boolean_not_valid": "Loqik olmayan",
"operator_not_multiple": "\"{1}\" operatoru çoxlu məna daşımır"
},
"invert": "invert"
};
QueryBuilder.defaults({ lang_code: 'az' });
})); |
/*!
* Native JavaScript for Bootstrap Carousel v3.0.14c (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Carousel = factory());
}(this, (function () { 'use strict';
var mouseHoverEvents = ('onmouseleave' in document) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ];
// determine support for passive events
var supportPassive = (function () {
// Test via a getter in the options object to see if the passive property is accessed
var result = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
result = true;
}
});
document.addEventListener('DOMContentLoaded', function wrap(){
document.removeEventListener('DOMContentLoaded', wrap, opts);
}, opts);
} catch (e) {}
return result;
})();
// general event options
var passiveHandler = supportPassive ? { passive: true } : false;
var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
var computedStyle = getComputedStyle(element),
propertyValue = computedStyle[transitionProperty],
durationValue = computedStyle[transitionDuration],
durationScale = durationValue.indexOf('ms') > -1 ? 1 : 1000,
duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat( durationValue ) * durationScale : 0;
return !isNaN(duration) ? duration : 0
}
var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
// emulateTransitionEnd
function emulateTransitionEnd(element,handler){
var called = 0,
endEvent = new Event( transitionEndEvent ),
duration = getElementTransitionDuration(element);
if ( duration ) {
element.addEventListener( transitionEndEvent, function transitionEndWrapper(e){
if ( e.target === element ) {
handler.apply( element, [e] );
element.removeEventListener( transitionEndEvent, transitionEndWrapper);
called = 1;
}
});
setTimeout(function() {
!called && element.dispatchEvent( endEvent );
}, duration + 17 );
} else { handler.apply( element, [endEvent]); }
}
function isElementInScrollRange(element) {
var bcr = element.getBoundingClientRect(),
viewportHeight = window.innerHeight || document.documentElement.clientHeight;
return bcr.top <= viewportHeight && bcr.bottom >= 0; // bottom && top
}
function queryElement(selector, parent) {
var lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function bootstrapCustomEvent( eventType, componentName, eventProperties ) {
var OriginalCustomEvent = new CustomEvent( eventType + '.bs.' + componentName, { cancelable: true } );
if ( typeof eventProperties !== 'undefined' ) {
Object.keys( eventProperties ).forEach( function (key) {
Object.defineProperty( OriginalCustomEvent, key, {
value: eventProperties[key]
});
});
}
return OriginalCustomEvent
}
function dispatchCustomEvent(customEvent){
this && this.dispatchEvent(customEvent);
}
// CAROUSEL DEFINITION
// ===================
function Carousel (element,options) {
// set options
options = options || {};
// bind
var self = this,
// internal variables
vars, ops,
// custom events
slideCustomEvent, slidCustomEvent,
// carousel elements
slides, leftArrow, rightArrow, indicator, indicators;
// handlers
function pauseHandler() {
if ( ops.interval !==false && !element.classList.contains('paused') ) {
element.classList.add('paused');
!vars.isSliding && ( clearInterval(vars.timer), vars.timer = null );
}
}
function resumeHandler() {
if ( ops.interval !== false && element.classList.contains('paused') ) {
element.classList.remove('paused');
!vars.isSliding && ( clearInterval(vars.timer), vars.timer = null );
!vars.isSliding && self.cycle();
}
}
function indicatorHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.target; // event target | the current active item
if ( eventTarget && !eventTarget.classList.contains('active') && eventTarget.getAttribute('data-slide-to') ) {
vars.index = parseInt( eventTarget.getAttribute('data-slide-to'));
} else { return false; }
self.slideTo( vars.index ); //Do the slide
}
function controlsHandler(e) {
e.preventDefault();
if (vars.isSliding) { return; }
var eventTarget = e.currentTarget || e.srcElement;
if ( eventTarget === rightArrow ) {
vars.index++;
} else if ( eventTarget === leftArrow ) {
vars.index--;
}
self.slideTo( vars.index ); //Do the slide
}
function keyHandler(ref) {
var which = ref.which;
if (vars.isSliding) { return; }
switch (which) {
case 39:
vars.index++;
break;
case 37:
vars.index--;
break;
default: return;
}
self.slideTo( vars.index ); //Do the slide
}
function toggleEvents(action) {
action = action ? 'addEventListener' : 'removeEventListener';
if ( ops.pause && ops.interval ) {
element[action]( mouseHoverEvents[0], pauseHandler, false );
element[action]( mouseHoverEvents[1], resumeHandler, false );
element[action]( 'touchstart', pauseHandler, passiveHandler );
element[action]( 'touchend', resumeHandler, passiveHandler );
}
ops.touch && slides.length > 1 && element[action]( 'touchstart', touchDownHandler, passiveHandler );
rightArrow && rightArrow[action]( 'click', controlsHandler,false );
leftArrow && leftArrow[action]( 'click', controlsHandler,false );
indicator && indicator[action]( 'click', indicatorHandler,false );
ops.keyboard && window[action]( 'keydown', keyHandler,false );
}
// touch events
function toggleTouchEvents(action) {
action = action ? 'addEventListener' : 'removeEventListener';
element[action]( 'touchmove', touchMoveHandler, passiveHandler );
element[action]( 'touchend', touchEndHandler, passiveHandler );
}
function touchDownHandler(e) {
if ( vars.isTouch ) { return; }
vars.touchPosition.startX = e.changedTouches[0].pageX;
if ( element.contains(e.target) ) {
vars.isTouch = true;
toggleTouchEvents(1);
}
}
function touchMoveHandler(e) {
if ( !vars.isTouch ) { e.preventDefault(); return; }
vars.touchPosition.currentX = e.changedTouches[0].pageX;
// cancel touch if more than one changedTouches detected
if ( e.type === 'touchmove' && e.changedTouches.length > 1 ) {
e.preventDefault();
return false;
}
}
function touchEndHandler (e) {
if ( !vars.isTouch || vars.isSliding ) { return }
vars.touchPosition.endX = vars.touchPosition.currentX || e.changedTouches[0].pageX;
if ( vars.isTouch ) {
if ( (!element.contains(e.target) || !element.contains(e.relatedTarget) )
&& Math.abs(vars.touchPosition.startX - vars.touchPosition.endX) < 75 ) {
return false;
} else {
if ( vars.touchPosition.currentX < vars.touchPosition.startX ) {
vars.index++;
} else if ( vars.touchPosition.currentX > vars.touchPosition.startX ) {
vars.index--;
}
vars.isTouch = false;
self.slideTo(vars.index);
}
toggleTouchEvents(); // remove
}
}
// private methods
function setActivePage(pageIndex) { //indicators
Array.from(indicators).map(function (x){x.classList.remove('active');});
indicators[pageIndex] && indicators[pageIndex].classList.add('active');
}
function transitionEndHandler(e){
if (vars.touchPosition){
var next = vars.index,
timeout = e && e.target !== slides[next] ? e.elapsedTime*1000+100 : 20,
activeItem = self.getActiveIndex(),
orientation = vars.direction === 'left' ? 'next' : 'prev';
vars.isSliding && setTimeout(function () {
if (vars.touchPosition){
vars.isSliding = false;
slides[next].classList.add('active');
slides[activeItem].classList.remove('active');
slides[next].classList.remove(("carousel-item-" + orientation));
slides[next].classList.remove(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.remove(("carousel-item-" + (vars.direction)));
dispatchCustomEvent.call(element, slidCustomEvent);
// check for element, might have been disposed
if ( !document.hidden && ops.interval && !element.classList.contains('paused') ) {
self.cycle();
}
}
}, timeout);
}
}
// public methods
self.cycle = function () {
if (vars.timer) {
clearInterval(vars.timer);
vars.timer = null;
}
vars.timer = setInterval(function () {
var idx = vars.index || self.getActiveIndex();
isElementInScrollRange(element) && (idx++, self.slideTo( idx ) );
}, ops.interval);
};
self.slideTo = function (next) {
if (vars.isSliding) { return; } // when controled via methods, make sure to check again
// the current active, orientation, event eventProperties
var activeItem = self.getActiveIndex(), orientation, eventProperties;
// first return if we're on the same item #227
if ( activeItem === next ) {
return;
// or determine slide direction
} else if ( (activeItem < next ) || (activeItem === 0 && next === slides.length -1 ) ) {
vars.direction = 'left'; // next
} else if ( (activeItem > next) || (activeItem === slides.length - 1 && next === 0 ) ) {
vars.direction = 'right'; // prev
}
// find the right next index
if ( next < 0 ) { next = slides.length - 1; }
else if ( next >= slides.length ){ next = 0; }
orientation = vars.direction === 'left' ? 'next' : 'prev'; // determine type
eventProperties = { relatedTarget: slides[next], direction: vars.direction, from: activeItem, to: next };
slideCustomEvent = bootstrapCustomEvent('slide', 'carousel', eventProperties);
slidCustomEvent = bootstrapCustomEvent('slid', 'carousel', eventProperties);
dispatchCustomEvent.call(element, slideCustomEvent); // here we go with the slide
if (slideCustomEvent.defaultPrevented) { return; } // discontinue when prevented
// update index
vars.index = next;
vars.isSliding = true;
clearInterval(vars.timer);
vars.timer = null;
setActivePage( next );
if ( getElementTransitionDuration(slides[next]) && element.classList.contains('slide') ) {
slides[next].classList.add(("carousel-item-" + orientation));
slides[next].offsetWidth;
slides[next].classList.add(("carousel-item-" + (vars.direction)));
slides[activeItem].classList.add(("carousel-item-" + (vars.direction)));
emulateTransitionEnd(slides[next], transitionEndHandler);
} else {
slides[next].classList.add('active');
slides[next].offsetWidth;
slides[activeItem].classList.remove('active');
setTimeout(function () {
vars.isSliding = false;
// check for element, might have been disposed
if ( ops.interval && element && !element.classList.contains('paused') ) {
self.cycle();
}
dispatchCustomEvent.call(element, slidCustomEvent);
}, 100 );
}
};
self.getActiveIndex = function () { return Array.from(slides).indexOf(element.getElementsByClassName('carousel-item active')[0]) || 0; };
self.dispose = function () {
var itemClasses = ['left','right','prev','next'];
Array.from(slides).map(function (slide,idx) {
slide.classList.contains('active') && setActivePage( idx );
itemClasses.map(function (cls) { return slide.classList.remove(("carousel-item-" + cls)); });
});
clearInterval(vars.timer);
toggleEvents();
vars = {};
ops = {};
delete element.Carousel;
};
// init
// initialization element
element = queryElement( element );
// reset on re-init
element.Carousel && element.Carousel.dispose();
// carousel elements
slides = element.getElementsByClassName('carousel-item');
leftArrow = element.getElementsByClassName('carousel-control-prev')[0];
rightArrow = element.getElementsByClassName('carousel-control-next')[0];
indicator = element.getElementsByClassName('carousel-indicators')[0];
indicators = indicator && indicator.getElementsByTagName( "LI" ) || [];
// invalidate when not enough items
if (slides.length < 2) { return }
// check options
var
// DATA API
intervalAttribute = element.getAttribute('data-interval'),
intervalData = intervalAttribute === 'false' ? 0 : parseInt(intervalAttribute),
touchData = element.getAttribute('data-touch') === 'false' ? 0 : 1,
pauseData = element.getAttribute('data-pause') === 'hover' || false,
keyboardData = element.getAttribute('data-keyboard') === 'true' || false,
// JS options
intervalOption = options.interval,
touchOption = options.touch;
// set instance options
ops = {};
ops.keyboard = options.keyboard === true || keyboardData;
ops.pause = (options.pause === 'hover' || pauseData) ? 'hover' : false; // false / hover
ops.touch = touchOption || touchData;
ops.interval = typeof intervalOption === 'number' ? intervalOption
: intervalOption === false || intervalData === 0 || intervalData === false ? 0
: isNaN(intervalData) ? 5000 // bootstrap carousel default interval
: intervalData;
// set first slide active if none
if (self.getActiveIndex()<0) {
slides.length && slides[0].classList.add('active');
indicators.length && setActivePage(0);
}
// set initial state
vars = {};
vars.direction = 'left';
vars.index = 0;
vars.timer = null;
vars.isSliding = false;
vars.isTouch = false;
vars.touchPosition = {
startX : 0,
currentX : 0,
endX : 0
};
// attach event handlers
toggleEvents(1);
// start to cycle if interval is set
if ( ops.interval ){ self.cycle(); }
// associate init object to target
element.Carousel = self;
}
return Carousel;
})));
|
export{X as CONTEXT,a6 as CUSTOM_UNITS,a4 as FLEX_GAP_SUPPORTED,P as NuAction,O as NuBase,M as Nude,a7 as ROOT_CONTEXT,a5 as STATES_MAP,a1 as assign,Y as behaviors,U as contrast,b as deepQuery,d as deepQueryAll,M as default,a0 as define,Q as elements,_ as helpers,a3 as hue,I as icons,i as isEqual,V as reduceMotion,Z as requestIdleCallback,m as routing,T as scheme,$ as styles,S as svg,a2 as units}from"./index-f1a98d77.js";
|
Object.defineProperty(exports,"__esModule",{value:true});const cloneDeep=require("lodash.clonedeep");const lGet=require("lodash.get");const merge=require("lodash.merge");const lSet=require("lodash.set");const Observable_1=require("rxjs/Observable");exports.Observable=Observable_1.Observable;const Subject_1=require("rxjs/Subject");exports.Subject=Subject_1.Subject;const async_types_1=require("../async-types");const promise_factory_1=require("../promise-factory");const request_store_1=require("../request-store");
const date_1=require("./date");const default_options_1=require("./default-options");const middleware_observers_1=require("./middleware-observers");const uniqueid=require("uniqueid");const getGenerateId=()=>{const asyncUniqueId=uniqueid(null,"-@@ASYNC_FLOW");return({action})=>`${asyncUniqueId()}--${action.type}`};
exports.createAsyncFlowMiddleware=(opts={metaKey:default_options_1.defaultOpts.metaKey,timeout:default_options_1.defaultOpts.timeout})=>{const {REQUEST,PENDING,FULFILLED,REJECTED,ABORTED,END}=async_types_1.getAsyncTypeConstants({types:opts.asyncTypes});const mwObservers=middleware_observers_1.createObservers({asyncTypes:{END,REQUEST}});const {generateId:generateIdMerged,metaKey,metaKeyRequestID,timeout}=Object.assign({},default_options_1.defaultOpts,opts);const generateId=generateIdMerged||getGenerateId();
const requestStore=new request_store_1.RequestStore;const middleware=()=>{return(next)=>{return(action)=>{const dispatchNormal=()=>next(action);const actionType=action.type;if(!actionType||lGet(action,["meta",metaKey,"enable"])===false)return dispatchNormal();const dispatchAsyncFlow=(actionArg)=>{mwObservers.before.rootSubject.next(actionArg);const dispatchResult=next(actionArg);mwObservers.after.rootSubject.next(dispatchResult);return dispatchResult};const metaRequestIdPath=["meta",metaKey,metaKeyRequestID];
const metaPromisePath=["meta",metaKey,"promise"];const handleEndAction=(suffixType,resolve)=>{const requestID=lGet(action,metaRequestIdPath);const theAsyncFlowPromise=lGet(action,metaPromisePath);if(!requestID||!theAsyncFlowPromise)return dispatchNormal();const dispatchResult=dispatchAsyncFlow(action);if(requestID){if(resolve)requestStore.resolve(requestID,action.payload);else requestStore.reject(requestID,action.payload);const actionEnd=merge({},action,{meta:{[metaKey]:{endActionType:actionType,
timeEnd:date_1.newDate()}},type:async_types_1.replaceSuffix(actionType,suffixType,END)});dispatchAsyncFlow(actionEnd)}else console.warn(`${action.type} - meta data not found, did you forget to send it?`);return dispatchResult};if(actionType.endsWith(REQUEST)){const actionClone=cloneDeep(action);let requestID=lGet(actionClone,metaRequestIdPath);if(!requestID||{}.hasOwnProperty.call(requestStore,requestID)){do requestID=generateId({action:actionClone});while({}.hasOwnProperty.call(requestStore,requestID));
lSet(actionClone,metaRequestIdPath,requestID)}const metaTimeoutKey=lGet(actionClone,["meta",metaKey,"timeoutRequest"]);const timeoutRequest=metaTimeoutKey||timeout;const {promise,reject,resolve}=promise_factory_1.createPromise();promise.timeout(timeoutRequest,"timeout").catch((er)=>{reject(er)}).finally(()=>{requestStore.delete(requestID)});const tmpRequestStoreAddPayload={[request_store_1.REQUEST_KEY_PROMISE]:promise,[request_store_1.REQUEST_KEY_RESOLVEFN]:resolve,[request_store_1.REQUEST_KEY_REJECTFN]:reject};
requestStore.add(requestID,tmpRequestStoreAddPayload);const addedActionMetaData={meta:{[metaKey]:{endActionType:null,promise,timeEnd:null,timeStart:date_1.newDate(),timeout,timeoutRequest}}};const pendingAction=merge({},actionClone,{type:async_types_1.replaceSuffix(actionType,REQUEST,PENDING)},addedActionMetaData);dispatchAsyncFlow(pendingAction);const newAction=merge({},actionClone,addedActionMetaData);return dispatchAsyncFlow(newAction)}else if(actionType.endsWith(FULFILLED))return handleEndAction(FULFILLED,
true);else if(actionType.endsWith(REJECTED))return handleEndAction(REJECTED,false);else if(actionType.endsWith(ABORTED))return handleEndAction(ABORTED,false);else return dispatchNormal()}}};return{middleware,observers:{after:{obsOnAll:mwObservers.after.obsOnAll,obsOnEnd:mwObservers.after.obsOnEnd,obsOnRequest:mwObservers.after.obsOnRequest},before:{obsOnAll:mwObservers.before.obsOnAll,obsOnEnd:mwObservers.before.obsOnEnd,obsOnRequest:mwObservers.before.obsOnRequest}}}}; |
'use strict';
var BooleanXform = require('../../../../../lib/xlsx/xform/simple/boolean-xform');
var testXformHelper = require('./../test-xform-helper');
var expectations = [
{
title: 'true',
create: function() { return new BooleanXform({tag: 'boolean', attr: 'val'}); },
preparedModel: true,
get parsedModel() { return this.preparedModel; },
xml: '<boolean/>',
tests: ['render', 'renderIn', 'parse']
},
{
title: 'false',
create: function() { return new BooleanXform({tag: 'boolean', attr: 'val'}); },
preparedModel: false,
xml: '',
tests: ['render', 'renderIn']
},
{
title: 'undefined',
create: function() { return new BooleanXform({tag: 'boolean', attr: 'val'}); },
preparedModel: undefined,
xml: '',
tests: ['render', 'renderIn']
}
];
describe('BooleanXform', function() {
testXformHelper(expectations);
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @namespace Phaser.Math.Easing.Bounce
*/
module.exports = {
In: require('./In'),
Out: require('./Out'),
InOut: require('./InOut')
};
|
'use strict';
var fs = require('fs');
var semverRegex = require('semver-regex');
var util = require('util');
var getConfig = require('./config').getConfig;
var config = getConfig();
var MAX_LENGTH = config.maxSubjectLength || 100;
var IGNORED = new RegExp(util.format('(^WIP)|(^%s$)', semverRegex().source));
// fixup! and squash! are part of Git, commits tagged with them are not intended to be merged, cf. https://git-scm.com/docs/git-commit
var PATTERN = /^((fixup! |squash! )?(\w+)(?:\(([^\)\s]+)\))?: (.+))(?:\n|$)/;
var MERGE_COMMIT_PATTERN = /^Merge /;
var error = function() {
// gitx does not display it
// http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails
// https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812
console[config.warnOnFail ? 'warn' : 'error']('INVALID COMMIT MSG: ' + util.format.apply(null, arguments));
};
exports.config = config;
exports.validateMessage = function validateMessage(raw, sourceFile) {
var types = config.types = config.types || 'conventional-commit-types';
var AUTO_FIX = config.autoFix && sourceFile;
// resolve types from a module
if (typeof types === 'string' && types !== '*') {
types = Object.keys(require(types).types);
}
var messageWithBody = (raw || '').split('\n').filter(function(str) {
return str.indexOf('#') !== 0;
}).join('\n');
var message = messageWithBody.split('\n').shift();
if (message === '') {
console.log('Aborting commit due to empty commit message.');
return false;
}
var isValid = true;
if (MERGE_COMMIT_PATTERN.test(message)) {
console.log('Merge commit detected.');
return true
}
if (IGNORED.test(message)) {
console.log('Commit message validation ignored.');
return true;
}
var match = PATTERN.exec(message);
if (!match) {
error('does not match "<type>(<scope>): <subject>" !');
isValid = false;
} else {
var firstLine = match[1];
var squashing = !!match[2];
var type = match[3];
var scope = match[4];
var subject = match[5];
var SUBJECT_PATTERN = new RegExp(config.subjectPattern || '.+');
var SUBJECT_PATTERN_ERROR_MSG = config.subjectPatternErrorMsg || 'subject does not match subject pattern!';
if (firstLine.length > MAX_LENGTH && !squashing) {
error('is longer than %d characters !', MAX_LENGTH);
isValid = false;
}
if (AUTO_FIX) {
type = lowercase(type);
}
if (types !== '*' && types.indexOf(type) === -1) {
error('"%s" is not allowed type ! Valid types are: %s', type, types.join(', '));
isValid = false;
}
isValid = validateScope(isValid, scope);
if (AUTO_FIX) {
subject = lowercaseFirstLetter(subject);
}
if (!SUBJECT_PATTERN.exec(subject)) {
error(SUBJECT_PATTERN_ERROR_MSG);
isValid = false;
}
}
// Some more ideas, do want anything like this ?
// - Validate the rest of the message (body, footer, BREAKING CHANGE annotations)
// - auto add empty line after subject ?
// - auto remove empty () ?
// - auto correct typos in type ?
// - store incorrect messages, so that we can learn
isValid = isValid || config.warnOnFail;
if (isValid) { // exit early and skip messaging logics
if (AUTO_FIX && !squashing) {
var scopeFixed = scope ? '(' + scope + ')' : '';
var firstLineFixed = type + scopeFixed + ': ' + subject;
if (firstLine !== firstLineFixed) {
var rawFixed = raw.replace(firstLine, firstLineFixed);
fs.writeFileSync(sourceFile, rawFixed);
}
}
return true;
}
var argInHelp = config.helpMessage && config.helpMessage.indexOf('%s') !== -1;
if (argInHelp) {
console.log(config.helpMessage, messageWithBody);
} else if (message) {
console.log(message);
}
if (!argInHelp && config.helpMessage) {
console.log(config.helpMessage);
}
return false;
};
function lowercase(string) {
return string.toLowerCase();
}
function lowercaseFirstLetter(string) {
return lowercase(string.charAt(0)) + string.slice(1);
}
function validateScope(isValid, scope) {
config.scope = config.scope || {};
var validateScopes = config.scope.validate || false;
var multipleScopesAllowed = config.scope.multiple || false;
var allowedScopes = config.scope.allowed || '*';
var scopeRequired = config.scope.required || false;
var scopes = scope ? scope.split(',') : [];
function validateIndividualScope(item) {
if (allowedScopes[0].trim() === '*') {
return;
}
if (allowedScopes.indexOf(item) === -1) {
error('"%s" is not an allowed scope ! Valid scope are: %s', item, allowedScopes.join(', '));
isValid = false;
}
}
if (validateScopes) {
if (scopeRequired && scopes.length === 0) {
error('a scope is required !');
isValid = false;
}
// If scope is not provided, we ignore the rest of the testing and do early
// return here.
if (scopes.length === 0) {
return isValid;
}
if (isValid && multipleScopesAllowed) {
scopes.forEach(validateIndividualScope);
}
if (isValid && !multipleScopesAllowed) {
if (scopes.length > 1) {
error('only one scope can be provided !');
isValid = false;
}
if (isValid) {
validateIndividualScope(scopes[0]);
}
}
}
return isValid;
};
|
'use strict';
var fillLeft = require('../fill-left');
var fillRight = require('../fill-right');
function s(value, sign, fill, width, precision) {
value = String(value);
if (precision) {
value = value.substr(0, precision);
}
if (!width) {
return value;
}
if (!fill) {
fill = ' ';
}
if (sign === '-') {
return fillRight(value, fill, width);
}
return fillLeft(value, fill, width);
}
module.exports = s;
|
/*jshint unused:false*/
var chai = require('chai'),
expect = chai.expect;
var req = require('request');
module.exports = function() {
'use strict';
var response;
this.When(/^I follow\-up a GET request to caddis at "([^"]*)"$/, function(url, callback) {
req.get(url, function(error, res, body) {
response = (typeof body === 'string') ? JSON.parse(body) : body;
callback();
});
});
this.Then(/^The response from the follow\-up is:$/, function(jsonString, callback) {
expect(response).to.deep.equal(JSON.parse(jsonString));
callback();
});
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.