Best JavaScript code snippet using pact-foundation-pact
network.ts
Source:network.ts
1import Random from 'java-random'2import ComponentsAlgorithm from './componentsAlgorithm'3import Clustering from './clustering'4import { calcSum, calcSumWithinRange, createDoubleArrayOfRandomNumbers, binarySearch } from './utils/arrays'5/**6 * Interface for specifying parameters when constructing a network.7 */8export interface NetworkConstructorParameters {9 /**10 * Number of nodes.11 */12 nNodes?: number13 /**14 * Indicates whether to set node weights equal to total edge weights.15 */16 setNodeWeightsToTotalEdgeWeights?: boolean17 /**18 * Node weights.19 */20 nodeWeights?: number[]21 /**22 * Edge list.23 */24 edges?: number[][]25 /**26 * Index of the first neighbor of each node.27 */28 firstNeighborIndices?: number[]29 /**30 * Neighbor list.31 */32 neighbors?: number[]33 /**34 * Edge weights.35 */36 edgeWeights?: number[]37 /**38 * Indicates whether the edge list is sorted.39 */40 sortedEdges?: boolean41 /**42 * Indicates whether to check the integrity of the network.43 */44 checkIntegrity?: boolean45}46/**47 * Network.48 *49 * Weighted nodes and weighted edges are supported. Directed edges are not50 * supported.51 *52 * Network objects are immutable.53 *54 * The adjacency matrix of the network is stored in a sparse compressed format.55 */56export default class Network {57 /**58 * Number of nodes.59 */60 public nNodes!: number61 /**62 * Node weights.63 */64 public nodeWeights!: number[]65 /**66 * Index of the first neighbor of each node in the `neighbors` array.67 *68 * The neighbors of node `i` are given by69 * `neighbors[firstNeighborIndices[i]], ...,70 * neighbors[firstNeighborIndices[i + 1] - 1]`.71 */72 public firstNeighborIndices!: number[]73 /**74 * Neighbors of each node.75 */76 public neighbors!: number[]77 /**78 * Edge weights.79 */80 public edgeWeights!: number[]81 /**82 * Total edge weight of self links.83 */84 public totalEdgeWeightSelfLinks!: number85 /**86 * Number of edges.87 *88 * Each edge is counted twice, once in each direction.89 */90 protected nEdges!: number91 /**92 * Constructs a network based on a list of edges or neighbors.93 *94 * @param parameters Network constructor parameters95 */96 public constructor (parameters?: NetworkConstructorParameters) {97 if (parameters) {98 if (parameters.nodeWeights && parameters.edges) {99 this.initializeNetworkBasedOnEdges(parameters.nodeWeights.length, parameters.nodeWeights, parameters.setNodeWeightsToTotalEdgeWeights, parameters.edges, parameters.edgeWeights, parameters.sortedEdges, parameters.checkIntegrity)100 } else if (parameters.nodeWeights && parameters.firstNeighborIndices && parameters.neighbors) {101 this.initializeNetworkBasedOnNeighbors(parameters.nodeWeights.length, parameters.nodeWeights, parameters.setNodeWeightsToTotalEdgeWeights, parameters.firstNeighborIndices, parameters.neighbors, parameters.edgeWeights, parameters.checkIntegrity)102 } else if (parameters.nNodes && parameters.edges) {103 this.initializeNetworkBasedOnEdges(parameters.nNodes, parameters.nodeWeights, parameters.setNodeWeightsToTotalEdgeWeights, parameters.edges, parameters.edgeWeights, parameters.sortedEdges, parameters.checkIntegrity)104 } else if (parameters.nNodes && parameters.firstNeighborIndices && parameters.neighbors) {105 this.initializeNetworkBasedOnNeighbors(parameters.nNodes, parameters.nodeWeights, parameters.setNodeWeightsToTotalEdgeWeights, parameters.firstNeighborIndices, parameters.neighbors, parameters.edgeWeights, parameters.checkIntegrity)106 }107 }108 }109 /**110 * Returns the number of nodes.111 *112 * @return Number of nodes113 */114 public getNNodes (): number {115 return this.nNodes116 }117 /**118 * Returns the total node weight.119 *120 * @return Total node weight121 */122 public getTotalNodeWeight (): number {123 return calcSum(this.nodeWeights)124 }125 /**126 * Returns the weight of each node.127 *128 * @return Weight of each node129 */130 public getNodeWeights (): number[] {131 return this.nodeWeights.slice()132 }133 /**134 * Returns the weight of a node.135 *136 * @param node Node137 *138 * @return Weight139 */140 public getNodeWeight (node: number): number {141 return this.nodeWeights[node]142 }143 /**144 * Returns the number of edges.145 *146 * Each edge is counted only once, even though an edge runs in two147 * directions. This means that the number of edges returned by148 * {@link getEdges} equals twice the number of edges returned by149 * {@link getNEdges}.150 *151 * @return Number of edges152 */153 public getNEdges (): number {154 return this.nEdges / 2155 }156 /**157 * Returns the number of neighbors per node.158 *159 * @return Number of neighbors per node160 */161 public getNNeighborsPerNode (): number[] {162 const nNeighborsPerNode = new Array<number>(this.nNodes)163 for (let i = 0; i < this.nNodes; i++) {164 nNeighborsPerNode[i] = this.firstNeighborIndices[i + 1] - this.firstNeighborIndices[i]165 }166 return nNeighborsPerNode167 }168 /**169 * Returns the number of neighbors of a node.170 *171 * @param node Node172 *173 * @return Number of neighbors174 */175 public getNNeighbors (node: number): number {176 return this.firstNeighborIndices[node + 1] - this.firstNeighborIndices[node]177 }178 /**179 * Returns the list of edges.180 *181 * Each edge is included twice, once in each direction. This means that the182 * number of edges returned by {@link getEdges} equals twice the number of183 * edges returned by {@link getNEdges}.184 *185 * The list of edges is returned in a two-dimensional array `edges`.186 * Edge `i` connects nodes `edges[0][i]` and `edges[1][i]`.187 *188 * @return List of edges189 */190 public getEdges (): number[][] {191 const edges = new Array<Array<number>>(2)192 edges[0] = new Array<number>(this.nEdges)193 for (let i = 0; i < this.nNodes; i++) {194 edges[0].fill(i, this.firstNeighborIndices[i], this.firstNeighborIndices[i + 1])195 }196 edges[1] = this.neighbors.slice()197 return edges198 }199 /**200 * Returns a list of neighbors per node.201 *202 * @return List of neighbors per node203 */204 public getNeighborsPerNode (): number[][] {205 const neighborsPerNode = new Array<Array<number>>(this.nNodes)206 for (let i = 0; i < this.nNodes; i++) {207 neighborsPerNode[i] = this.neighbors.slice(this.firstNeighborIndices[i], this.firstNeighborIndices[i + 1])208 }209 return neighborsPerNode210 }211 /**212 * Returns the list of neighbors of a node.213 *214 * @param node Node215 *216 * @return List of neighbors217 */218 public getNeighbors (node: number): number[] {219 return this.neighbors.slice(this.firstNeighborIndices[node], this.firstNeighborIndices[node + 1])220 }221 /**222 * Returns the total edge weight per node. The total edge weight of a node223 * equals the sum of the weights of the edges between the node and its224 * neighbors.225 *226 * @return Total edge weight per node227 */228 public getTotalEdgeWeightPerNode (): number[] {229 return this.getTotalEdgeWeightPerNodeHelper()230 }231 /**232 * Returns the total edge weight.233 *234 * Each edge is considered only once, even though an edge runs in two235 * directions. This means that the sum of the edge weights returned by236 * {@link getEdgeWeights} equals twice the total edge weight returned by237 * {@link getTotalEdgeWeight}.238 *239 * Edge weights of self links are not included.240 *241 * @param node Node242 *243 * @return Total edge weight244 */245 public getTotalEdgeWeight (node?: number): number {246 return node === undefined ? calcSum(this.edgeWeights) / 2 : calcSumWithinRange(this.edgeWeights, this.firstNeighborIndices[node], this.firstNeighborIndices[node + 1])247 }248 /**249 * Returns a list of edge weights per node. These are the weights of the250 * edges between a node and its neighbors.251 *252 * @return List of edge weights per node253 */254 public getEdgeWeightsPerNode (): number[][] {255 const edgeWeightsPerNode = new Array<Array<number>>(this.nNodes)256 for (let i = 0; i < this.nNodes; i++) {257 edgeWeightsPerNode[i] = this.edgeWeights.slice(this.firstNeighborIndices[i], this.firstNeighborIndices[i + 1])258 }259 return edgeWeightsPerNode260 }261 /**262 * Returns the list of edge weights of a node. These are the weights of the263 * edges between the node and its neighbors.264 *265 * @param node Node266 *267 * @return List of edge weights268 */269 public getEdgeWeights (node?: number): number[] {270 return node === undefined ? this.edgeWeights.slice() : this.edgeWeights.slice(this.firstNeighborIndices[node], this.firstNeighborIndices[node + 1])271 }272 /**273 * Returns the total edge weight of self links.274 *275 * @return Total edge weight of self links276 */277 public getTotalEdgeWeightSelfLinks (): number {278 return this.totalEdgeWeightSelfLinks279 }280 /**281 * Creates a copy of the network, but without node weights.282 *283 * Each node is assigned a weight of 1.284 *285 * @return Network without node weights286 */287 public createNetworkWithoutNodeWeights (): Network {288 const networkWithoutNodeWeights = new Network()289 networkWithoutNodeWeights.nNodes = this.nNodes290 networkWithoutNodeWeights.nEdges = this.nEdges291 networkWithoutNodeWeights.nodeWeights = new Array<number>(this.nNodes).fill(1)292 networkWithoutNodeWeights.firstNeighborIndices = this.firstNeighborIndices293 networkWithoutNodeWeights.neighbors = this.neighbors294 networkWithoutNodeWeights.edgeWeights = this.edgeWeights295 networkWithoutNodeWeights.totalEdgeWeightSelfLinks = this.totalEdgeWeightSelfLinks296 return networkWithoutNodeWeights297 }298 /**299 * Creates a copy of the network, but without edge weights.300 *301 * Each edge is assigned a weight of 1.302 *303 * @return Network without edge weights304 */305 public createNetworkWithoutEdgeWeights (): Network {306 const networkWithoutEdgeWeights = new Network()307 networkWithoutEdgeWeights.nNodes = this.nNodes308 networkWithoutEdgeWeights.nEdges = this.nEdges309 networkWithoutEdgeWeights.nodeWeights = this.nodeWeights310 networkWithoutEdgeWeights.firstNeighborIndices = this.firstNeighborIndices311 networkWithoutEdgeWeights.neighbors = this.neighbors312 networkWithoutEdgeWeights.edgeWeights = new Array<number>(this.nEdges).fill(1)313 networkWithoutEdgeWeights.totalEdgeWeightSelfLinks = 0314 return networkWithoutEdgeWeights315 }316 /**317 * Creates a copy of the network, but without node and edge weights.318 *319 * Each node is assigned a weight of 1, and each edge is assigned a weight320 * of 1.321 *322 * @return Network without node and edge weights323 */324 public createNetworkWithoutNodeAndEdgeWeights (): Network {325 const networkWithoutNodeAndEdgeWeights = new Network()326 networkWithoutNodeAndEdgeWeights.nNodes = this.nNodes327 networkWithoutNodeAndEdgeWeights.nEdges = this.nEdges328 networkWithoutNodeAndEdgeWeights.nodeWeights = new Array<number>(this.nNodes).fill(1)329 networkWithoutNodeAndEdgeWeights.firstNeighborIndices = this.firstNeighborIndices330 networkWithoutNodeAndEdgeWeights.neighbors = this.neighbors331 networkWithoutNodeAndEdgeWeights.edgeWeights = new Array<number>(this.nEdges).fill(1)332 networkWithoutNodeAndEdgeWeights.totalEdgeWeightSelfLinks = 0333 return networkWithoutNodeAndEdgeWeights334 }335 /**336 * Creates a copy of the network in which the edge weights have been337 * normalized using the association strength.338 *339 * The normalized weight `a'[i][j]` of the edge between nodes `i` and `j` is340 * given by341 *342 * ```343 * a'[i][j] = a[i][j] / (n[i] * n[j] / (2 * m)),344 * ```345 *346 * where `a[i][j]` is the non-normalized weight of the edge between nodes `i`347 * and `j`, `n[i]` is the weight of node `i`, and `m` is half the total node348 * weight.349 *350 * If each node's weight equals the total weight of the edges between the351 * node and its neighbors, the edge weights are normalized by dividing them352 * by the expected edge weights in the random configuration model.353 *354 * The node weights are set to 1.355 *356 * @return Normalized network357 */358 public createNormalizedNetworkUsingAssociationStrength (): Network {359 const normalizedNetwork = new Network()360 normalizedNetwork.nNodes = this.nNodes361 normalizedNetwork.nEdges = this.nEdges362 normalizedNetwork.nodeWeights = new Array<number>(this.nNodes).fill(1)363 normalizedNetwork.firstNeighborIndices = this.firstNeighborIndices364 normalizedNetwork.neighbors = this.neighbors365 normalizedNetwork.edgeWeights = new Array<number>(this.nEdges)366 const totalNodeWeight = this.getTotalNodeWeight()367 for (let i = 0; i < this.nNodes; i++) {368 for (let j = this.firstNeighborIndices[i]; j < this.firstNeighborIndices[i + 1]; j++) {369 normalizedNetwork.edgeWeights[j] = this.edgeWeights[j] / ((this.nodeWeights[i] * this.nodeWeights[this.neighbors[j]]) / totalNodeWeight)370 }371 }372 normalizedNetwork.totalEdgeWeightSelfLinks = 0373 return normalizedNetwork374 }375 /**376 * Creates a copy of the network in which the edge weights have been377 * normalized using fractionalization.378 *379 * The normalized weight `a'[i][j]` of the edge between nodes `i` and `j` is380 * given by381 *382 * ```383 * a'[i][j] = a[i][j] * (n / n[i] + n / n[j]) / 2,384 * ```385 *386 * where `a[i][j]` is the non-normalized weight of the edge between nodes `i`387 * and `j`, `n[i]` is the weight of node `i`, and `n` is the number of nodes.388 *389 * The node weights are set to 1.390 *391 * @return Normalized network392 */393 public createNormalizedNetworkUsingFractionalization (): Network {394 const normalizedNetwork = new Network()395 normalizedNetwork.nNodes = this.nNodes396 normalizedNetwork.nEdges = this.nEdges397 normalizedNetwork.nodeWeights = new Array<number>(this.nNodes).fill(1)398 normalizedNetwork.firstNeighborIndices = this.firstNeighborIndices399 normalizedNetwork.neighbors = this.neighbors400 normalizedNetwork.edgeWeights = new Array<number>(this.nEdges)401 for (let i = 0; i < this.nNodes; i++) {402 for (let j = this.firstNeighborIndices[i]; j < this.firstNeighborIndices[i + 1]; j++) {403 normalizedNetwork.edgeWeights[j] = this.edgeWeights[j] / (2 / (this.nNodes / this.nodeWeights[i] + this.nNodes / this.nodeWeights[this.neighbors[j]]))404 }405 }406 normalizedNetwork.totalEdgeWeightSelfLinks = 0407 return normalizedNetwork408 }409 /**410 * Creates a copy of the network that has been pruned in order to have a411 * specified maximum number of edges.412 *413 * Only the edges with the highest weights are retained in the pruned414 * network. In case of ties, the edges to be retained are selected415 * randomly.416 *417 * @param maxNEdges Maximum number of edges418 * @param random Random number generator419 *420 * @return Pruned network421 */422 public createPrunedNetwork (maxNEdges: number, random: Random = new Random()): Network {423 maxNEdges *= 2424 if (maxNEdges >= this.nEdges) return this425 const edgeWeights = new Array<number>(this.nEdges / 2).fill(0)426 let i = 0427 for (let j = 0; j < this.nNodes; j++) {428 let k = this.firstNeighborIndices[j]429 while ((k < this.firstNeighborIndices[j + 1]) && (this.neighbors[k] < j)) {430 edgeWeights[i] = this.edgeWeights[k]431 i++432 k++433 }434 }435 edgeWeights.sort((a, b) => a - b)436 const edgeWeightThreshold = edgeWeights[(this.nEdges - maxNEdges) / 2]437 let nEdgesAboveThreshold = 0438 while (edgeWeights[this.nEdges / 2 - nEdgesAboveThreshold - 1] > edgeWeightThreshold) {439 nEdgesAboveThreshold++440 }441 let nEdgesAtThreshold = 0442 while ((nEdgesAboveThreshold + nEdgesAtThreshold < this.nEdges / 2) && (edgeWeights[this.nEdges / 2 - nEdgesAboveThreshold - nEdgesAtThreshold - 1] === edgeWeightThreshold)) {443 nEdgesAtThreshold++444 }445 const randomNumbers = createDoubleArrayOfRandomNumbers(this.nNodes * this.nNodes, random)446 const randomNumbersEdgesAtThreshold = new Array<number>(nEdgesAtThreshold).fill(0)447 i = 0448 for (let j = 0; j < this.nNodes; j++) {449 let k = this.firstNeighborIndices[j]450 while ((k < this.firstNeighborIndices[j + 1]) && (this.neighbors[k] < j)) {451 if (this.edgeWeights[k] === edgeWeightThreshold) {452 randomNumbersEdgesAtThreshold[i] = this.getRandomNumber(j, this.neighbors[k], randomNumbers)453 i++454 }455 k++456 }457 }458 randomNumbersEdgesAtThreshold.sort((a, b) => a - b)459 const randomNumberThreshold = randomNumbersEdgesAtThreshold[nEdgesAboveThreshold + nEdgesAtThreshold - maxNEdges / 2]460 const prunedNetwork = new Network()461 prunedNetwork.nNodes = this.nNodes462 prunedNetwork.nEdges = maxNEdges463 prunedNetwork.nodeWeights = this.nodeWeights464 prunedNetwork.firstNeighborIndices = new Array<number>(this.nNodes + 1).fill(0)465 prunedNetwork.neighbors = new Array<number>(maxNEdges).fill(0)466 prunedNetwork.edgeWeights = new Array<number>(maxNEdges).fill(0)467 i = 0468 for (let j = 0; j < this.nNodes; j++) {469 for (let k = this.firstNeighborIndices[j]; k < this.firstNeighborIndices[j + 1]; k++) {470 if ((this.edgeWeights[k] > edgeWeightThreshold) || ((this.edgeWeights[k] === edgeWeightThreshold) && (this.getRandomNumber(j, this.neighbors[k], randomNumbers) >= randomNumberThreshold))) {471 prunedNetwork.neighbors[i] = this.neighbors[k]472 prunedNetwork.edgeWeights[i] = this.edgeWeights[k]473 i++474 }475 }476 prunedNetwork.firstNeighborIndices[j + 1] = i477 }478 prunedNetwork.totalEdgeWeightSelfLinks = 0479 return prunedNetwork480 }481 /**482 * Creates an induced subnetwork for specified nodes.483 *484 * @param nodes Nodes485 *486 * @return Subnetwork487 */488 public createSubnetworkForNodes1 (nodes: number[]): Network {489 const subnetwork = new Network()490 subnetwork.nNodes = nodes.length491 if (subnetwork.nNodes === 1) {492 subnetwork.nEdges = 0493 subnetwork.nodeWeights = new Array<number>(1)494 subnetwork.nodeWeights[0] = this.nodeWeights[nodes[0]]495 subnetwork.firstNeighborIndices = new Array<number>(2).fill(0)496 subnetwork.neighbors = new Array<number>(0)497 subnetwork.edgeWeights = new Array<number>(0)498 } else {499 const subnetworkNodes = new Array<number>(this.nNodes).fill(-1)500 for (let i = 0; i < nodes.length; i++) {501 subnetworkNodes[nodes[i]] = i502 }503 subnetwork.nEdges = 0504 subnetwork.nodeWeights = new Array<number>(subnetwork.nNodes)505 subnetwork.firstNeighborIndices = new Array<number>(subnetwork.nNodes + 1).fill(0)506 const subnetworkNeighbors = new Array<number>(this.nEdges).fill(0)507 const subnetworkEdgeWeights = new Array<number>(this.nEdges).fill(0)508 for (let i = 0; i < subnetwork.nNodes; i++) {509 const j = nodes[i]510 subnetwork.nodeWeights[i] = this.nodeWeights[j]511 for (let k = this.firstNeighborIndices[j]; k < this.firstNeighborIndices[j + 1]; k++) {512 if (subnetworkNodes[this.neighbors[k]] >= 0) {513 subnetworkNeighbors[subnetwork.nEdges] = subnetworkNodes[this.neighbors[k]]514 subnetworkEdgeWeights[subnetwork.nEdges] = this.edgeWeights[k]515 subnetwork.nEdges++516 }517 }518 subnetwork.firstNeighborIndices[i + 1] = subnetwork.nEdges519 }520 subnetwork.neighbors = subnetworkNeighbors.slice(0, subnetwork.nEdges)521 subnetwork.edgeWeights = subnetworkEdgeWeights.slice(0, subnetwork.nEdges)522 }523 subnetwork.totalEdgeWeightSelfLinks = 0524 return subnetwork525 }526 /**527 * Creates an induced subnetwork for specified nodes.528 *529 * @param nodesInSubnetwork Indicates the nodes to be included in the530 * subnetwork.531 *532 * @return Subnetwork533 */534 public createSubnetworkForNodes2 (nodesInSubnetwork: boolean[]): Network {535 let i = 0536 for (let j = 0; j < this.nNodes; j++) {537 if (nodesInSubnetwork[j]) {538 i++539 }540 }541 const nodes = new Array<number>(i).fill(0)542 i = 0543 for (let j = 0; j < this.nNodes; j++) {544 if (nodesInSubnetwork[j]) {545 nodes[i] = j546 i++547 }548 }549 return this.createSubnetworkForNodes1(nodes)550 }551 /**552 * Creates an induced subnetwork for a specified cluster in a clustering.553 *554 * If subnetworks need to be created for all clusters in a clustering, it555 * is more efficient to use {@link createSubnetworks}.556 *557 * @param clustering Clustering558 * @param cluster Cluster559 *560 * @return Subnetwork561 */562 public createSubnetworkForCluster (clustering: Clustering, cluster: number): Network {563 const nodesPerCluster = clustering.getNodesPerCluster()564 const subnetworkNodes = new Array<number>(this.nNodes).fill(0)565 const subnetworkNeighbors = new Array<number>(this.nEdges).fill(0)566 const subnetworkEdgeWeights = new Array<number>(this.nEdges).fill(0)567 return this.createSubnetwork(clustering, cluster, nodesPerCluster[cluster], subnetworkNodes, subnetworkNeighbors, subnetworkEdgeWeights)568 }569 /**570 * Creates induced subnetworks for the clusters in a clustering.571 *572 * @param clustering Clustering573 *574 * @return Subnetworks575 */576 public createSubnetworks (clustering: Clustering): Network[] {577 const subnetworks = new Array<Network>(clustering.nClusters)578 const nodesPerCluster = clustering.getNodesPerCluster()579 const subnetworkNodes = new Array<number>(this.nNodes).fill(0)580 const subnetworkNeighbors = new Array<number>(this.nEdges).fill(0)581 const subnetworkEdgeWeights = new Array<number>(this.nEdges).fill(0)582 for (let i = 0; i < clustering.nClusters; i++) {583 subnetworks[i] = this.createSubnetwork(clustering, i, nodesPerCluster[i], subnetworkNodes, subnetworkNeighbors, subnetworkEdgeWeights)584 }585 return subnetworks586 }587 /**588 * Creates an induced subnetwork of the largest connected component.589 *590 * @return Subnetwork591 */592 public createSubnetworkLargestComponent (): Network {593 return this.createSubnetworkForCluster(this.identifyComponents(), 0)594 }595 /**596 * Creates a reduced (or aggregate) network based on a clustering.597 *598 * Each node in the reduced network corresponds to a cluster of nodes in599 * the original network. The weight of a node in the reduced network equals600 * the sum of the weights of the nodes in the corresponding cluster in the601 * original network. The weight of an edge between two nodes in the reduced602 * network equals the sum of the weights of the edges between the nodes in603 * the two corresponding clusters in the original network.604 *605 * @param clustering Clustering606 *607 * @return Reduced network608 */609 public createReducedNetwork (clustering: Clustering): Network {610 const reducedNetwork = new Network()611 reducedNetwork.nNodes = clustering.nClusters612 reducedNetwork.nEdges = 0613 reducedNetwork.nodeWeights = new Array<number>(clustering.nClusters).fill(0)614 reducedNetwork.firstNeighborIndices = new Array<number>(clustering.nClusters + 1).fill(0)615 reducedNetwork.totalEdgeWeightSelfLinks = this.totalEdgeWeightSelfLinks616 const reducedNetworkNeighbors1 = new Array<number>(this.nEdges).fill(0)617 const reducedNetworkEdgeWeights1 = new Array<number>(this.nEdges).fill(0)618 const reducedNetworkNeighbors2 = new Array<number>(clustering.nClusters - 1).fill(0)619 const reducedNetworkEdgeWeights2 = new Array<number>(clustering.nClusters).fill(0)620 const nodesPerCluster = clustering.getNodesPerCluster()621 for (let i = 0; i < clustering.nClusters; i++) {622 let j = 0623 for (let k = 0; k < nodesPerCluster[i].length; k++) {624 const l = nodesPerCluster[i][k]625 reducedNetwork.nodeWeights[i] += this.nodeWeights[l]626 for (let m = this.firstNeighborIndices[l]; m < this.firstNeighborIndices[l + 1]; m++) {627 const n = clustering.clusters[this.neighbors[m]]628 if (n !== i) {629 if (reducedNetworkEdgeWeights2[n] === 0) {630 reducedNetworkNeighbors2[j] = n631 j++632 }633 reducedNetworkEdgeWeights2[n] += this.edgeWeights[m]634 } else {635 reducedNetwork.totalEdgeWeightSelfLinks += this.edgeWeights[m]636 }637 }638 }639 for (let k = 0; k < j; k++) {640 reducedNetworkNeighbors1[reducedNetwork.nEdges + k] = reducedNetworkNeighbors2[k]641 reducedNetworkEdgeWeights1[reducedNetwork.nEdges + k] = reducedNetworkEdgeWeights2[reducedNetworkNeighbors2[k]]642 reducedNetworkEdgeWeights2[reducedNetworkNeighbors2[k]] = 0643 }644 reducedNetwork.nEdges += j645 reducedNetwork.firstNeighborIndices[i + 1] = reducedNetwork.nEdges646 }647 reducedNetwork.neighbors = reducedNetworkNeighbors1.slice(0, reducedNetwork.nEdges)648 reducedNetwork.edgeWeights = reducedNetworkEdgeWeights1.slice(0, reducedNetwork.nEdges)649 return reducedNetwork650 }651 /**652 * Identifies the connected components of the network.653 *654 * @return Connected components655 */656 public identifyComponents (): Clustering {657 const componentsAlgorithm = new ComponentsAlgorithm()658 return componentsAlgorithm.findClustering(this)659 }660 /**661 * Checks the integrity of the network.662 *663 * It is checked whether:664 *665 * <ul>666 * <li>variables have a correct value,</li>667 * <li>arrays have a correct length,</li>668 * <li>edges are sorted correctly,</li>669 * <li>edges are stored in both directions.</li>670 * </ul>671 *672 * An exception is thrown if the integrity of the network is violated.673 *674 * @throws An illegal argument was provided in the construction of the network.675 */676 private checkIntegrity (): void {677 // Check whether variables have a correct value and arrays have a correct length.678 if (this.nNodes < 0) {679 throw new Error('nNodes must be non-negative.')680 }681 if (this.nEdges < 0) {682 throw new Error('nEdges must be non-negative.')683 }684 if (this.nEdges % 2 === 1) {685 throw new Error('nEdges must be even.')686 }687 if (this.nodeWeights.length !== this.nNodes) {688 throw new Error('Length of nodeWeight array must be equal to nNodes.')689 }690 if (this.firstNeighborIndices.length !== this.nNodes + 1) {691 throw new Error('Length of firstNeighborIndices array must be equal to nNodes + 1.')692 }693 if (this.firstNeighborIndices[0] !== 0) {694 throw new Error('First element of firstNeighborIndices array must be equal to 0.')695 }696 if (this.firstNeighborIndices[this.nNodes] !== this.nEdges) {697 throw new Error('Last element of firstNeighborIndices array must be equal to nEdges.')698 }699 if (this.neighbors.length !== this.nEdges) {700 throw new Error('Length of neighbors array must be equal to nEdges.')701 }702 if (this.edgeWeights.length !== this.nEdges) {703 throw new Error('Length of edgeWeights array must be equal to nEdges.')704 }705 // Check whether edges are sorted correctly.706 for (let i = 0; i < this.nNodes; i++) {707 if (this.firstNeighborIndices[i + 1] < this.firstNeighborIndices[i]) {708 throw new Error('Elements of firstNeighborIndices array must be in non-decreasing order.')709 }710 for (let j = this.firstNeighborIndices[i]; j < this.firstNeighborIndices[i + 1]; j++) {711 const k = this.neighbors[j]712 if (k < 0) {713 throw new Error('Elements of neighbors array must have non-negative values.')714 } else if (k >= this.nNodes) {715 throw new Error('Elements of neighbors array must have values less than nNodes.')716 }717 if (j > this.firstNeighborIndices[i]) {718 const l = this.neighbors[j - 1]719 if (k < l) {720 throw new Error('For each node, corresponding elements of neighbors array must be in increasing order.')721 } else if (k === l) {722 throw new Error('For each node, corresponding elements of neighbors array must not include duplicate values.')723 }724 }725 }726 }727 // Check whether edges are stored in both directions.728 const checked = new Array<boolean>(this.nEdges)729 for (let i = 0; i < this.nNodes; i++) {730 for (let j = this.firstNeighborIndices[i]; j < this.firstNeighborIndices[i + 1]; j++) {731 if (!checked[j]) {732 const k = this.neighbors[j]733 const l = binarySearch(this.neighbors, this.firstNeighborIndices[k], this.firstNeighborIndices[k + 1], i)734 if (l < 0) {735 throw new Error('Edges must be stored in both directions.')736 }737 if (this.edgeWeights[j] !== this.edgeWeights[l]) {738 throw new Error('Edge weights must be the same in both directions.')739 }740 checked[j] = true741 checked[l] = true742 }743 }744 }745 }746 private initializeNetworkBasedOnEdges (nNodes: number, nodeWeights: number[] | undefined, setNodeWeightsToTotalEdgeWeights: boolean | undefined, edges: number[][], edgeWeights: number[] | undefined, sortedEdges: boolean | undefined, checkIntegrity: boolean | undefined): void {747 let i: number748 if (!sortedEdges) {749 const edges2 = [new Array<number>(2 * edges[0].length), new Array<number>(2 * edges[0].length)]750 const edgeWeights2 = edgeWeights !== undefined ? new Array<number>(2 * edges[0].length) : undefined751 i = 0752 for (let j = 0; j < edges[0].length; j++) {753 edges2[0][i] = edges[0][j]754 edges2[1][i] = edges[1][j]755 if (edgeWeights !== undefined && edgeWeights2 !== undefined) edgeWeights2[i] = edgeWeights[j]756 i++757 if (edges[0][j] !== edges[1][j]) {758 edges2[0][i] = edges[1][j]759 edges2[1][i] = edges[0][j]760 if (edgeWeights !== undefined && edgeWeights2 !== undefined) edgeWeights2[i] = edgeWeights[j]761 i++762 }763 }764 edges[0] = edges2[0].slice(0, i)765 edges[1] = edges2[1].slice(0, i)766 if (edgeWeights !== undefined && edgeWeights2 !== undefined) edgeWeights = edgeWeights2.slice(0, i)767 this.sortEdges(edges, edgeWeights)768 }769 this.nNodes = nNodes770 this.nEdges = 0771 this.firstNeighborIndices = new Array<number>(nNodes + 1).fill(0)772 this.neighbors = new Array<number>(edges[0].length).fill(0)773 this.edgeWeights = new Array<number>(edges[0].length).fill(0)774 this.totalEdgeWeightSelfLinks = 0775 i = 1776 for (let j = 0; j < edges[0].length; j++) {777 if (edges[0][j] !== edges[1][j]) {778 for (; i <= edges[0][j]; i++) {779 this.firstNeighborIndices[i] = this.nEdges780 }781 this.neighbors[this.nEdges] = edges[1][j]782 this.edgeWeights[this.nEdges] = edgeWeights !== undefined ? edgeWeights[j] : 1783 this.nEdges++784 } else {785 this.totalEdgeWeightSelfLinks += edgeWeights !== undefined ? edgeWeights[j] : 1786 }787 }788 for (; i <= nNodes; i++) {789 this.firstNeighborIndices[i] = this.nEdges790 }791 this.neighbors = this.neighbors.slice(0, this.nEdges)792 this.edgeWeights = this.edgeWeights.slice(0, this.nEdges)793 if (typeof nodeWeights !== 'undefined') {794 this.nodeWeights = nodeWeights.slice()795 } else {796 this.nodeWeights = setNodeWeightsToTotalEdgeWeights ? this.getTotalEdgeWeightPerNodeHelper() : new Array<number>(this.nNodes).fill(1)797 }798 if (checkIntegrity) this.checkIntegrity()799 }800 private initializeNetworkBasedOnNeighbors (nNodes: number, nodeWeights: number[] | undefined, setNodeWeightsToTotalEdgeWeights: boolean | undefined, firstNeighborIndices: number[], neighbors: number[], edgeWeights: number[] | undefined, checkIntegrity: boolean | undefined): void {801 this.nNodes = nNodes802 this.nEdges = neighbors.length803 this.firstNeighborIndices = firstNeighborIndices.slice()804 this.neighbors = neighbors.slice()805 this.edgeWeights = edgeWeights ? edgeWeights.slice() : new Array<number>(this.nEdges).fill(1)806 this.totalEdgeWeightSelfLinks = 0807 if (nodeWeights !== undefined) {808 this.nodeWeights = nodeWeights.slice()809 } else {810 this.nodeWeights = setNodeWeightsToTotalEdgeWeights ? this.getTotalEdgeWeightPerNodeHelper() : new Array<number>(this.nNodes).fill(1)811 }812 if (checkIntegrity) this.checkIntegrity()813 }814 private getTotalEdgeWeightPerNodeHelper (): number[] {815 const totalEdgeWeightPerNode = new Array<number>(this.nNodes)816 for (let i = 0; i < this.nNodes; i++) {817 totalEdgeWeightPerNode[i] = calcSumWithinRange(this.edgeWeights, this.firstNeighborIndices[i], this.firstNeighborIndices[i + 1])818 }819 return totalEdgeWeightPerNode820 }821 private getRandomNumber (node1: number, node2: number, randomNumbers: number[]): number {822 let i: number823 let j: number824 if (node1 < node2) {825 i = node1826 j = node2827 } else {828 i = node2829 j = node1830 }831 return randomNumbers[i * this.nNodes + j]832 }833 private createSubnetwork (clustering: Clustering, cluster: number, nodes: number[], subnetworkNodes: number[], subnetworkNeighbors: number[], subnetworkEdgeWeights: number[]): Network {834 const subnetwork = new Network()835 subnetwork.nNodes = nodes.length836 if (subnetwork.nNodes === 1) {837 subnetwork.nEdges = 0838 subnetwork.nodeWeights = new Array<number>(1)839 subnetwork.nodeWeights[0] = this.nodeWeights[nodes[0]]840 subnetwork.firstNeighborIndices = new Array<number>(2).fill(0)841 subnetwork.neighbors = new Array<number>(0)842 subnetwork.edgeWeights = new Array<number>(0)843 } else {844 for (let i = 0; i < nodes.length; i++) {845 subnetworkNodes[nodes[i]] = i846 }847 subnetwork.nEdges = 0848 subnetwork.nodeWeights = new Array<number>(subnetwork.nNodes)849 subnetwork.firstNeighborIndices = new Array<number>(subnetwork.nNodes + 1).fill(0)850 for (let i = 0; i < subnetwork.nNodes; i++) {851 const j = nodes[i]852 subnetwork.nodeWeights[i] = this.nodeWeights[j]853 for (let k = this.firstNeighborIndices[j]; k < this.firstNeighborIndices[j + 1]; k++) {854 if (clustering.clusters[this.neighbors[k]] === cluster) {855 subnetworkNeighbors[subnetwork.nEdges] = subnetworkNodes[this.neighbors[k]]856 subnetworkEdgeWeights[subnetwork.nEdges] = this.edgeWeights[k]857 subnetwork.nEdges++858 }859 }860 subnetwork.firstNeighborIndices[i + 1] = subnetwork.nEdges861 }862 subnetwork.neighbors = subnetworkNeighbors.slice(0, subnetwork.nEdges)863 subnetwork.edgeWeights = subnetworkEdgeWeights.slice(0, subnetwork.nEdges)864 }865 subnetwork.totalEdgeWeightSelfLinks = 0866 return subnetwork867 }868 private sortEdges (edges: number[][], edgeWeights?: number[]): void {869 function compareEdges (edges: number[][], i: number, j: number): number {870 if (edges[0][i] > edges[0][j]) return 1871 if (edges[0][i] < edges[0][j]) return -1872 if (edges[1][i] > edges[1][j]) return 1873 if (edges[1][i] < edges[1][j]) return -1874 return 0875 }876 const nEdges = edges[0].length877 // Determine sorting order.878 const indices = [...Array(nEdges).keys()]879 indices.sort((a, b) => compareEdges(edges, a, b))880 // Sort edges.881 const edgesSorted = new Array<Array<number>>(2)882 edgesSorted[0] = new Array<number>(nEdges)883 edgesSorted[1] = new Array<number>(nEdges)884 for (let i = 0; i < nEdges; i++) {885 edgesSorted[0][i] = edges[0][indices[i]]886 edgesSorted[1][i] = edges[1][indices[i]]887 }888 edges[0] = edgesSorted[0]889 edges[1] = edgesSorted[1]890 // Sort edge weights.891 if (edgeWeights !== undefined) {892 const edgeWeightsSorted = new Array<number>(nEdges)893 for (let i = 0; i < nEdges; i++) {894 edgeWeightsSorted[i] = edgeWeights[indices[i]]895 }896 Object.assign(edgeWeights, edgeWeightsSorted)897 }898 }...
TaskModelLeaderboardCardWrapper.js
Source:TaskModelLeaderboardCardWrapper.js
1/*2 * Copyright (c) Facebook, Inc. and its affiliates.3 * This source code is licensed under the MIT license found in the4 * LICENSE file in the root directory of this source tree.5 */6import React from "react";7import TaskModelLeaderboardCard from "./TaskModelLeaderboardCard";8import { useParams } from "react-router-dom";9/**10 *11 * This is a wrapper around TaskModelLeaderboardCard.js which allows to extract out the logic for initializing weights12 * and fetching leaderboard data. A custom task leaderboard can be created simply by passing in custom functions for13 * initializing weights and fetching data.14 *15 * @param getInitialWeights Function that defines how weights for metrics and datasets are to be initialized16 * @param fetchLeaderboardData Function that defines how the leaderboard data is to be fetched17 * @returns {function(*)} A functional component that uses the custom function passed to taskModelLeaderboardCardWrapper18 * and renders the TaskModelLeaderboardCard.19 */20const taskModelLeaderboardCardWrapper = (21 getInitialWeights,22 fetchLeaderboardData23) => {24 return (props) => {25 const { forkOrSnapshotName } = useParams();26 const dataFromProps = {27 leaderboardName: forkOrSnapshotName,28 history: props.history,29 snapshotData: props.snapshotData,30 };31 return (32 <TaskModelLeaderboardCard33 {...props}34 getInitialWeights={(...args) =>35 getInitialWeights(...args, dataFromProps)36 }37 fetchLeaderboardData={(...args) =>38 fetchLeaderboardData(...args, dataFromProps)39 }40 />41 );42 };43};44const loadDefaultWeights = (metricIdToDataObj, datasetIdToDataObj, task) => {45 task.ordered_metrics.forEach((m) => {46 metricIdToDataObj[m.name] = {47 id: m.name,48 label: m.name,49 weight: m.default_weight,50 unit: m.unit,51 };52 });53 task.ordered_scoring_datasets.forEach((ds) => {54 datasetIdToDataObj[ds.id] = {55 id: ds.id,56 weight: ds.default_weight,57 name: ds.name,58 };59 });60};61export const getOrderedWeights = (metricWeights, datasetWeights) => {62 const metricSum = metricWeights?.reduce(63 (acc, entry) => acc + entry.weight,64 065 );66 const orderedMetricWeights = metricWeights?.map((entry) =>67 metricSum === 0 ? 0.0 : entry.weight / metricSum68 );69 const dataSetSum = datasetWeights?.reduce(70 (acc, entry) => acc + entry.weight,71 072 );73 const orderedDatasetWeights = datasetWeights?.map((entry) =>74 dataSetSum === 0 ? 0.0 : entry.weight / dataSetSum75 );76 return { orderedMetricWeights, orderedDatasetWeights };77};78const loadDefaultData = (79 api,80 taskId,81 pageLimit,82 page,83 sort,84 metrics,85 datasetWeights,86 updateResultCallback87) => {88 const { orderedMetricWeights, orderedDatasetWeights } = getOrderedWeights(89 metrics,90 datasetWeights91 );92 if (93 orderedMetricWeights &&94 orderedDatasetWeights &&95 orderedMetricWeights.length > 0 &&96 orderedDatasetWeights.length > 097 ) {98 api99 .getDynaboardScores(100 taskId,101 pageLimit,102 page * pageLimit,103 sort.field,104 sort.direction,105 orderedMetricWeights,106 orderedDatasetWeights107 )108 .then(109 (result) => updateResultCallback(result),110 (error) => {111 console.log(error);112 updateResultCallback(null);113 }114 );115 }116};117const getOrderedWeightObjects = (118 metricIdToDataObj,119 datasetIdToDataObj,120 task121) => {122 const orderedMetricWeights = task.ordered_metrics.map(123 (m) => metricIdToDataObj[m.name]124 );125 const orderedDatasetWeights = task.ordered_scoring_datasets.map(126 (ds) => datasetIdToDataObj[ds.id]127 );128 return { orderedMetricWeights, orderedDatasetWeights };129};130export const TaskModelDefaultLeaderboard = taskModelLeaderboardCardWrapper(131 (task, api, setWeightsCallback) => {132 const metricIdToDataObj = {};133 const datasetIdToDataObj = {};134 loadDefaultWeights(metricIdToDataObj, datasetIdToDataObj, task);135 setWeightsCallback(136 getOrderedWeightObjects(metricIdToDataObj, datasetIdToDataObj, task)137 );138 },139 loadDefaultData140);141export const TaskModelForkLeaderboard = taskModelLeaderboardCardWrapper(142 (task, api, setWeightsCallback, dataFromProps) => {143 const metricIdToDataObj = {};144 const datasetIdToDataObj = {};145 /* We first load the default weights for metrics and datasets. This is useful to load the default weight for146 * a metric/dataset which was added after the creation of a fork.147 */148 loadDefaultWeights(metricIdToDataObj, datasetIdToDataObj, task);149 const { leaderboardName, history } = dataFromProps;150 /* Through this API, the default weights for metrics and datasets get overwritten by the weights saved during151 * creation of the fork.152 */153 api.getLeaderboardConfiguration(task.id, leaderboardName).then(154 (result) => {155 const configuration_json = JSON.parse(result.configuration_json);156 configuration_json.metricWeights.forEach((m) => {157 if (m.id in metricIdToDataObj) {158 metricIdToDataObj[m.id].weight = m.weight;159 }160 });161 configuration_json.datasetWeights.forEach((d) => {162 if (d.id in datasetIdToDataObj) {163 datasetIdToDataObj[d.id].weight = d.weight;164 }165 });166 setWeightsCallback({167 ...getOrderedWeightObjects(168 metricIdToDataObj,169 datasetIdToDataObj,170 task171 ),172 description: result.desc,173 });174 },175 (error) => {176 console.log(error);177 if (error && error.status_code === 404) {178 history.replace({179 pathname: `/tasks/${task.task_code}`,180 });181 }182 setWeightsCallback(183 getOrderedWeightObjects(metricIdToDataObj, datasetIdToDataObj, task)184 );185 }186 );187 },188 loadDefaultData189);190export const TaskModelSnapshotLeaderboard = taskModelLeaderboardCardWrapper(191 (task, api, setWeightsCallback, dataFromProps) => {192 const { snapshotData } = dataFromProps;193 const { metricWeights, datasetWeights } = snapshotData;194 setWeightsCallback({195 orderedMetricWeights: metricWeights,196 orderedDatasetWeights: datasetWeights,197 });198 },199 (200 api,201 taskId,202 pageLimit,203 page,204 sort,205 metrics,206 datasetWeights,207 updateResultCallback,208 dataFromProps209 ) => {210 const { snapshotData } = dataFromProps;211 updateResultCallback({212 data: snapshotData.data.slice(page * pageLimit, (page + 1) * pageLimit),213 count: snapshotData.count,214 sort: snapshotData.miscInfoJson.sort,215 });216 }...
neural.js
Source:neural.js
1// heavily inspired by https://github.com/mlruzic/jake-the-snake 2class Neural {3 static calculateOutput(input, weights, f = Neural.sigmoid) {4 return Neural.calculateLayers(input, weights, f)[weights.length - 1];5 }6 static calculateLayers(input, weights, f = Neural.sigmoid) {7 const layers = [];8 let layer = input.map((e, i) => f(e * weights[0][i][0]));9 layers.push(layer);10 for (let i = 1; i < weights.length; i++) {11 const outputs = [];12 for (let j = 0; j < weights[i].length; j++) {13 let output = 0;14 for (let k = 0; k < weights[i][j].length; k++) {15 output += weights[i][j][k] * layer[k];16 }17 outputs.push(f(output));18 }19 layer = outputs;20 layers.push(layer);21 }22 return layers;23 }24 // neuronCounts - array of neron counts per layer e.g. [2,4,4,5]25 // returns array of per-layer arrays with weights where values are determined by value function26 static createWeights(neuronCounts, value) {27 const result = [];28 for (let i = 0; i < neuronCounts.length; i++) {29 const previousCount = neuronCounts[i - 1] || 1;30 const currentCount = neuronCounts[i];31 const layerWeights = [];32 for (let j = 0; j < currentCount; j++) {33 const weights = [];34 for (let k = 0; k < previousCount; k++) {35 weights.push(value(i, j, k));36 }37 layerWeights.push(weights);38 }39 result.push(layerWeights);40 }41 return result;42 }43 static copyWeights(weights) {44 const result = [];45 for (let i = 0; i < weights.length; i++) {46 const iWeights = [];47 for (let j = 0; j < weights[i].length; j++) {48 const jWeights = [];49 for (let k = 0; k < weights[i][j].length; k++) {50 jWeights.push(weights[i][j][k]);51 }52 iWeights.push(jWeights);53 }54 result.push(iWeights);55 }56 return result;57 }58 static isSame(weightsA, weightsB) {59 for (let i = 0; i < weightsA.length; i++) {60 for (let j = 0; j < weightsA[i].length; j++) {61 for (let k = 0; k < weightsA[i][j].length; k++) {62 if (weightsA[i][j][k] !== weightsB[i][j][k]) {63 return false;64 }65 }66 }67 }68 return true;69 }70 static sigmoid(x) {71 return 1 / (1 + Math.exp(-x));72 }73 static swish(x) {74 return x / (1 + Math.exp(-x));75 }76 static test() {77 const assert = (actual, expected) => {78 const actualJson = JSON.stringify(actual);79 const expectedJson = JSON.stringify(expected);80 if (actualJson !== expectedJson) {81 throw `Fail: actual='${actualJson}', expected='${expectedJson}'`;82 }83 }84 // --------85 let x = 0;86 let weights = Neural.createWeights([2, 3, 4, 5], () => ++x);87 assert(weights, [[[1], [2]], [[3, 4], [5, 6], [7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]], [[21, 22, 23, 24], [25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36], [37, 38, 39, 40]]]);88 weights = Neural.createWeights([3, 2, 5], (i, j, k) => `${i}j${j}k${k}`);89 assert(weights, [[["0j0k0"], ["0j1k0"], ["0j2k0"]], [["1j0k0", "1j0k1", "1j0k2"], ["1j1k0", "1j1k1", "1j1k2"]], [["2j0k0", "2j0k1"], ["2j1k0", "2j1k1"], ["2j2k0", "2j2k1"], ["2j3k0", "2j3k1"], ["2j4k0", "2j4k1"]]]);90 weights = Neural.createWeights([3, 2, 2, 4], (i) => i);91 assert(weights, [[[0], [0], [0]], [[1, 1, 1], [1, 1, 1]], [[2, 2], [2, 2]], [[3, 3], [3, 3], [3, 3], [3, 3]]]);92 // --------93 x = 0;94 weights = Neural.createWeights([2, 3], () => ++x);95 let output = Neural.calculateOutput([-2, 2], weights, (x) => x);96 assert(output, [3 * (1 * -2) + 4 * (2 * 2), 5 * (1 * -2) + 6 * (2 * 2), 7 * (1 * -2) + 8 * (2 * 2)]);97 // --------98 x = 0;99 weights = Neural.createWeights([2, 3], () => ++x);100 output = Neural.calculateOutput([-2, 2], weights, (x) => 7 * x);101 assert(output, [7 * 3 * (7 * 1 * -2) + 7 * 4 * (7 * 2 * 2), 7 * 5 * (7 * 1 * -2) + 7 * 6 * (7 * 2 * 2), 7 * 7 * (7 * 1 * -2) + 7 * 8 * (7 * 2 * 2)]);102 // --------103 x = 0;104 weights = Neural.createWeights([2, 3, 4], () => ++x);105 assert(weights, [[[1], [2]], [[3, 4], [5, 6], [7, 8]], [[9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]]]);106 let copy = Neural.copyWeights(weights);107 assert(copy, weights);108 // --------109 x = 0;110 weights = Neural.createWeights([2, 3, 4], () => ++x);111 output = Neural.calculateOutput([-2, 2], weights, (x) => 7 * x);112 assert(output, [146804, 190022, 233240, 276458]);113 let layers = Neural.calculateLayers([-2, 2], weights, (x) => 7 * x);114 assert(layers, [[-14, 28], [490, 686, 882], [146804, 190022, 233240, 276458]]);115 }116}...
Using AI Code Generation
1const { Matchers } = require('@pact-foundation/pact');2const { somethingLike: like } = Matchers;3const { like: likeString } = Matchers;4const { like: likeNumber } = Matchers;5const { like: likeBoolean } = Matchers;6const { like: likeArray } = Matchers;7const { like: likeObject } = Matchers;8const { like: likeDate } = Matchers;9const { like: likeTimestamp } = Matchers;10const { like: likeBase64 } = Matchers;11const { like: likeUuid } = Matchers;12const { like: likeHexadecimal } = Matchers;13const { like: likeEmail } = Matchers;14const { like: likeIpv4 } = Matchers;15const { like: likeIpv6 } = Matchers;16const { like: likeUrl } = Matchers;17const { like: likeHostname } = Matchers;18const { like: likeJson } = Matchers;19const { like: likeXml } = Matchers;20const { like: likeRegex } = Matchers;21const { like: likeTerm } = Matchers;22const { like: likeDecimal } = Matchers;23const { like: likeVarchar } = Matchers;24const { like: likeChar } = Matchers;25const { like: likeTime } = Matchers;26const { like: likeTimestampWithTimezone } = Matchers;27const { like: likeTimestampWithoutTimezone } = Matchers;28const { like: likeTimestampWithLocalTimezone } = Matchers;29const { like: likeTimestampWithLocalTimezone } = Matchers;30const { like: likeTimestampWithoutTimezone } = Matchers;31const { like: likeTimestampWithLocalTimezone } = Matchers;32const { like: likeTimestampWithLocalTimezone } = Matchers;33const { like: likeTimestampWithoutTimezone } = Matchers;34const { like: likeTimestampWithLocalTimezone } = Matchers;35const { like: likeTimestampWithLocalTimezone } = Matchers;36const { like: likeTimestampWithoutTimezone } = Matchers;37const { like: likeTimestampWithLocalTimezone } = Matchers;38const { like: likeTimestampWithLocalTimezone } = Matchers;39const { like: likeTimestampWithoutTimezone } = Matchers;40const { like: likeTimestampWithLocalTimezone } = Matchers;41const { like: likeTimestampWithLocalTimezone } = Matchers;42const { like: likeTimestamp
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!