Commit ceb47f1d authored by limm's avatar limm
Browse files

add third_party

parent 1cb25232
cmake_minimum_required(VERSION 3.8)
list (APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(DetectVersion)
cmake_policy(SET CMP0048 NEW) ## set VERSION as documented by the project() command.
cmake_policy(SET CMP0076 NEW) ## accept new policy
set(CMAKE_CXX_STANDARD 11) ## compile with C++11 support
set(CMAKE_CXX_STANDARD_REQUIRED ON)
project(phmap VERSION ${DETECTED_PHMAP_VERSION} LANGUAGES CXX)
set(PHMAP_DIR parallel_hashmap)
set(PHMAP_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/${PHMAP_DIR}/phmap.h
${CMAKE_CURRENT_SOURCE_DIR}/${PHMAP_DIR}/phmap_base.h
${CMAKE_CURRENT_SOURCE_DIR}/${PHMAP_DIR}/phmap_bits.h
${CMAKE_CURRENT_SOURCE_DIR}/${PHMAP_DIR}/phmap_utils.h
${CMAKE_CURRENT_SOURCE_DIR}/${PHMAP_DIR}/phmap_config.h)
set(CMAKE_SUPPRESS_REGENERATION true) ## suppress ZERO_CHECK project
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
include(helpers)
include_directories("${CMAKE_CURRENT_SOURCE_DIR}")
add_library(${PROJECT_NAME} INTERFACE)
target_sources(${PROJECT_NAME} INTERFACE ${PHMAP_HEADERS})
target_include_directories(
${PROJECT_NAME} INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>)
install(
DIRECTORY ${PROJECT_SOURCE_DIR}/${PHMAP_DIR}/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PHMAP_DIR})
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}-targets)
export(EXPORT ${PROJECT_NAME}-targets
FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake")
## ------------------------- building tests and examples -------------
option(PHMAP_BUILD_TESTS "Whether or not to build the tests" ON)
option(PHMAP_BUILD_EXAMPLES "Whether or not to build the examples" ON)
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
endif()
if (PHMAP_BUILD_TESTS)
include(cmake/DownloadGTest.cmake)
include_directories(${PROJECT_SOURCE_DIR})
check_target(gtest)
check_target(gtest_main)
check_target(gmock)
enable_testing()
## ---------------- regular hash maps ----------------------------
phmap_cc_test(NAME compressed_tuple SRCS "tests/compressed_tuple_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME container_memory SRCS "tests/container_memory_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME hash_policy_testing SRCS "tests/hash_policy_testing_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME node_hash_policy SRCS "tests/node_hash_policy_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME raw_hash_set SRCS "tests/raw_hash_set_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME raw_hash_set_allocator SRCS "tests/raw_hash_set_allocator_test.cc"
DEPS gmock_main)
## ---------------- regular hash maps ----------------------------
phmap_cc_test(NAME flat_hash_set SRCS "tests/flat_hash_set_test.cc"
COPTS "-DUNORDERED_SET_CXX17" DEPS gmock_main)
phmap_cc_test(NAME flat_hash_map SRCS "tests/flat_hash_map_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME node_hash_map SRCS "tests/node_hash_map_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME node_hash_set SRCS "tests/node_hash_set_test.cc"
COPTS "-DUNORDERED_SET_CXX17" DEPS gmock_main)
## --------------- parallel hash maps -----------------------------------------------
phmap_cc_test(NAME parallel_flat_hash_map SRCS "tests/parallel_flat_hash_map_test.cc"
COPTS "-DUNORDERED_MAP_CXX17" DEPS gmock_main)
phmap_cc_test(NAME parallel_flat_hash_set SRCS "tests/parallel_flat_hash_set_test.cc"
COPTS "-DUNORDERED_SET_CXX17" DEPS gmock_main)
phmap_cc_test(NAME parallel_node_hash_map SRCS "tests/parallel_node_hash_map_test.cc"
DEPS gmock_main)
phmap_cc_test(NAME parallel_node_hash_set SRCS "tests/parallel_node_hash_set_test.cc"
COPTS "-DUNORDERED_SET_CXX17" DEPS gmock_main)
phmap_cc_test(NAME parallel_flat_hash_map_mutex SRCS "tests/parallel_flat_hash_map_mutex_test.cc"
COPTS "-DUNORDERED_MAP_CXX17" DEPS gmock_main)
phmap_cc_test(NAME dump_load SRCS "tests/dump_load_test.cc"
COPTS "-DUNORDERED_MAP_CXX17" DEPS gmock_main)
phmap_cc_test(NAME erase_if SRCS "tests/erase_if_test.cc"
COPTS "-DUNORDERED_MAP_CXX17" DEPS gmock_main)
## --------------- btree -----------------------------------------------
phmap_cc_test(NAME btree SRCS "tests/btree_test.cc"
CLOPTS "-w" DEPS gmock_main)
endif()
if (PHMAP_BUILD_EXAMPLES)
if(NOT MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wdisabled-optimization -Winit-self -Wlogical-op -Wmissing-include-dirs -Woverloaded-virtual -Wredundant-decls -Wshadow -Wstrict-null-sentinel -Wswitch-default -Wno-unused -Wno-unknown-warning-option -Wno-gnu-zero-variadic-macro-arguments")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /Zc:__cplusplus")
endif()
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
add_executable(ex_allmaps examples/allmaps.cc phmap.natvis)
add_executable(ex_basic examples/basic.cc phmap.natvis)
add_executable(ex_bench examples/bench.cc phmap.natvis)
add_executable(ex_emplace examples/emplace.cc phmap.natvis)
if (MSVC)
add_executable(ex_lazy_emplace_l examples/lazy_emplace_l.cc phmap.natvis)
endif()
add_executable(ex_serialize examples/serialize.cc phmap.natvis)
target_include_directories(ex_serialize PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../cereal/include>)
add_executable(ex_hash_std examples/hash_std.cc phmap.natvis)
add_executable(ex_hash_value examples/hash_value.cc phmap.natvis)
add_executable(ex_two_files examples/f1.cc examples/f2.cc phmap.natvis)
add_executable(ex_insert_bench examples/insert_bench.cc phmap.natvis)
add_executable(ex_knucleotide examples/knucleotide.cc phmap.natvis)
add_executable(ex_dump_load examples/dump_load.cc phmap.natvis)
add_executable(ex_btree examples/btree.cc phmap.natvis)
add_executable(ex_matt examples/matt.cc phmap.natvis)
target_link_libraries(ex_knucleotide Threads::Threads)
target_link_libraries(ex_bench Threads::Threads)
endif()
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.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.
<img src="https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/phash.png?raw=true" width="120" align="middle">
# The Parallel Hashmap
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache-yellow.svg)](https://opensource.org/licenses/Apache-2.0) [![Linux](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/linux.yml/badge.svg)](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/linux.yml) [![MacOS](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/macos.yml/badge.svg)](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/macos.yml) [![Windows](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/windows.yml/badge.svg)](https://github.com/greg7mdp/parallel-hashmap/actions/workflows/windows.yml)
## Overview
This repository aims to provide a set of excellent **hash map** implementations, as well as a **btree** alternative to std::map and std::set, with the following characteristics:
- **Header only**: nothing to build, just copy the `parallel_hashmap` directory to your project and you are good to go.
- **drop-in replacement** for `std::unordered_map`, `std::unordered_set`, `std::map` and `std::set`
- Compiler with **C++11 support** required, **C++14 and C++17 APIs are provided (such as `try_emplace`)**
- **Very efficient**, significantly faster than your compiler's unordered map/set or Boost's, or than [sparsepp](https://github.com/greg7mdp/sparsepp)
- **Memory friendly**: low memory usage, although a little higher than [sparsepp](https://github.com/greg7mdp/sparsepp)
- Supports **heterogeneous lookup**
- Easy to **forward declare**: just include `phmap_fwd_decl.h` in your header files to forward declare Parallel Hashmap containers [note: this does not work currently for hash maps with pointer keys]
- **Dump/load** feature: when a `flat` hash map stores data that is `std::trivially_copyable`, the table can be dumped to disk and restored as a single array, very efficiently, and without requiring any hash computation. This is typically about 10 times faster than doing element-wise serialization to disk, but it will use 10% to 60% extra disk space. See `examples/serialize.cc`. _(flat hash map/set only)_
- **Tested** on Windows (vs2015 & vs2017, vs2019, Intel compiler 18 and 19), linux (g++ 4.8.4, 5, 6, 7, 8, clang++ 3.9, 4.0, 5.0) and MacOS (g++ and clang++) - click on travis and appveyor icons above for detailed test status.
- Automatic support for **boost's hash_value()** method for providing the hash function (see `examples/hash_value.h`). Also default hash support for `std::pair` and `std::tuple`.
- **natvis** visualization support in Visual Studio _(hash map/set only)_
@byronhe kindly provided this [Chinese translation](https://byronhe.com/post/2020/11/10/parallel-hashmap-btree-fast-multi-thread-intro/) of the README.md.
## Fast *and* memory friendly
Click here [For a full writeup explaining the design and benefits of the Parallel Hashmap](https://greg7mdp.github.io/parallel-hashmap/).
The hashmaps and btree provided here are built upon those open sourced by Google in the Abseil library. The hashmaps use closed hashing, where values are stored directly into a memory array, avoiding memory indirections. By using parallel SSE2 instructions, these hashmaps are able to look up items by checking 16 slots in parallel, allowing the implementation to remain fast even when the table is filled up to 87.5% capacity.
> **IMPORTANT:** This repository borrows code from the [abseil-cpp](https://github.com/abseil/abseil-cpp) repository, with modifications, and may behave differently from the original. This repository is an independent work, with no guarantees implied or provided by the authors. Please visit [abseil-cpp](https://github.com/abseil/abseil-cpp) for the official Abseil libraries.
## Installation
Copy the parallel_hashmap directory to your project. Update your include path. That's all.
If you are using Visual Studio, you probably want to add `phmap.natvis` to your projects. This will allow for a clear display of the hash table contents in the debugger.
> A cmake configuration files (CMakeLists.txt) is provided for building the tests and examples. Command for building and running the tests is: `mkdir build && cd build && cmake -DPHMAP_BUILD_TESTS=ON -DPHMAP_BUILD_EXAMPLES=ON .. && cmake --build . && make test`
## Example
```c++
#include <iostream>
#include <string>
#include <parallel_hashmap/phmap.h>
using phmap::flat_hash_map;
int main()
{
// Create an unordered_map of three strings (that map to strings)
flat_hash_map<std::string, std::string> email =
{
{ "tom", "tom@gmail.com"},
{ "jeff", "jk@gmail.com"},
{ "jim", "jimg@microsoft.com"}
};
// Iterate and print keys and values
for (const auto& n : email)
std::cout << n.first << "'s email is: " << n.second << "\n";
// Add a new entry
email["bill"] = "bg@whatever.com";
// and print it
std::cout << "bill's email is: " << email["bill"] << "\n";
return 0;
}
```
## Various hash maps and their pros and cons
The header `parallel_hashmap/phmap.h` provides the implementation for the following eight hash tables:
- phmap::flat_hash_set
- phmap::flat_hash_map
- phmap::node_hash_set
- phmap::node_hash_map
- phmap::parallel_flat_hash_set
- phmap::parallel_flat_hash_map
- phmap::parallel_node_hash_set
- phmap::parallel_node_hash_map
The header `parallel_hashmap/btree.h` provides the implementation for the following btree-based ordered containers:
- phmap::btree_set
- phmap::btree_map
- phmap::btree_multiset
- phmap::btree_multimap
The btree containers are direct ports from Abseil, and should behave exactly the same as the Abseil ones, modulo small differences (such as supporting std::string_view instead of absl::string_view, and being forward declarable).
When btrees are mutated, values stored within can be moved in memory. This means that pointers or iterators to values stored in btree containers can be invalidated when that btree is modified. This is a significant difference with `std::map` and `std::set`, as the std containers do offer a guarantee of pointer stability. The same is true for the 'flat' hash maps and sets.
The full types with template parameters can be found in the [parallel_hashmap/phmap_fwd_decl.h](https://raw.githubusercontent.com/greg7mdp/parallel-hashmap/master/parallel_hashmap/phmap_fwd_decl.h) header, which is useful for forward declaring the Parallel Hashmaps when necessary.
**Key decision points for hash containers:**
- The `flat` hash maps will move the keys and values in memory. So if you keep a pointer to something inside a `flat` hash map, this pointer may become invalid when the map is mutated. The `node` hash maps don't, and should be used instead if this is a problem.
- The `flat` hash maps will use less memory, and usually be faster than the `node` hash maps, so use them if you can. the exception is when the values inserted in the hash map are large (say more than 100 bytes [*needs testing*]) and costly to move.
- The `parallel` hash maps are preferred when you have a few hash maps that will store a very large number of values. The `non-parallel` hash maps are preferred if you have a large number of hash maps, each storing a relatively small number of values.
- The benefits of the `parallel` hash maps are:
a. reduced peak memory usage (when resizing), and
b. multithreading support (and inherent internal parallelism)
**Key decision points for btree containers:**
Btree containers are ordered containers, which can be used as alternatives to `std::map` and `std::set`. They store multiple values in each tree node, and are therefore more cache friendly and use significantly less memory.
Btree containers will usually be preferable to the default red-black trees of the STL, except when:
- pointer stability or iterator stability is required
- the value_type is large and expensive to move
When an ordering is not needed, a hash container is typically a better choice than a btree one.
## Changes to Abseil's hashmaps
- The default hash framework is std::hash, not absl::Hash. However, if you prefer the default to be the Abseil hash framework, include the Abseil headers before `phmap.h` and define the preprocessor macro `PHMAP_USE_ABSL_HASH`.
- The `erase(iterator)` and `erase(const_iterator)` both return an iterator to the element following the removed element, as does the std::unordered_map. A non-standard `void _erase(iterator)` is provided in case the return value is not needed.
- No new types, such as `absl::string_view`, are provided. All types with a `std::hash<>` implementation are supported by phmap tables (including `std::string_view` of course if your compiler provides it).
- The Abseil hash tables internally randomize a hash seed, so that the table iteration order is non-deterministic. This can be useful to prevent *Denial Of Service* attacks when a hash table is used for a customer facing web service, but it can make debugging more difficult. The *phmap* hashmaps by default do **not** implement this randomization, but it can be enabled by adding `#define PHMAP_NON_DETERMINISTIC 1` before including the header `phmap.h` (as is done in raw_hash_set_test.cc).
- Unlike the Abseil hash maps, we do an internal mixing of the hash value provided. This prevents serious degradation of the hash table performance when the hash function provided by the user has poor entropy distribution. The cost in performance is very minimal, and this helps provide reliable performance even with *imperfect* hash functions.
## Memory usage
| type | memory usage | additional *peak* memory usage when resizing |
|-----------------------|-------------------|-----------------------------------------------|
| flat tables | ![flat_mem_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/flat_mem_usage.png?raw=true) | ![flat_peak_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/flat_peak.png?raw=true) |
| node tables | ![node_mem_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/node_mem_usage.png?raw=true) | ![node_peak_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/node_peak.png?raw=true) |
| parallel flat tables | ![flat_mem_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/flat_mem_usage.png?raw=true) | ![parallel_flat_peak](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/parallel_flat_peak.png?raw=true) |
| parallel node tables | ![node_mem_usage](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/node_mem_usage.png?raw=true) | ![parallel_node_peak](https://github.com/greg7mdp/parallel-hashmap/blob/master/html/img/parallel_node_peak.png?raw=true) |
- *size()* is the number of values in the container, as returned by the size() method
- *load_factor()* is the ratio: `size() / bucket_count()`. It varies between 0.4375 (just after the resize) to 0.875 (just before the resize). The size of the bucket array doubles at each resize.
- the value 9 comes from `sizeof(void *) + 1`, as the *node* hash maps store one pointer plus one byte of metadata for each entry in the bucket array.
- flat tables store the values, plus one byte of metadata per value), directly into the bucket array, hence the `sizeof(C::value_type) + 1`.
- the additional peak memory usage (when resizing) corresponds the the old bucket array (half the size of the new one, hence the 0.5), which contains the values to be copied to the new bucket array, and which is freed when the values have been copied.
- the *parallel* hashmaps, when created with a template parameter N=4, create 16 submaps. When the hash values are well distributed, and in single threaded mode, only one of these 16 submaps resizes at any given time, hence the factor `0.03` roughly equal to `0.5 / 16`
## Iterator invalidation for hash containers
The rules are the same as for `std::unordered_map`, and are valid for all the phmap hash containers:
| Operations | Invalidated |
|-------------------------------------------|----------------------------|
| All read only operations, swap, std::swap | Never |
| clear, rehash, reserve, operator= | Always |
| insert, emplace, emplace_hint, operator[] | Only if rehash triggered |
| erase | Only to the element erased |
## Iterator invalidation for btree containers
Unlike for `std::map` and `std::set`, any mutating operation may invalidate existing iterators to btree containers.
| Operations | Invalidated |
|-------------------------------------------|----------------------------|
| All read only operations, swap, std::swap | Never |
| clear, operator= | Always |
| insert, emplace, emplace_hint, operator[] | Yes |
| erase | Yes |
## Example 2 - providing a hash function for a user-defined class
In order to use a flat_hash_set or flat_hash_map, a hash function should be provided. This can be done with one of the following methods:
- Provide a hash functor via the HashFcn template parameter
- As with boost, you may add a `hash_value()` friend function in your class.
For example:
```c++
#include <parallel_hashmap/phmap_utils.h> // minimal header providing phmap::HashState()
#include <string>
using std::string;
struct Person
{
bool operator==(const Person &o) const
{
return _first == o._first && _last == o._last && _age == o._age;
}
friend size_t hash_value(const Person &p)
{
return phmap::HashState().combine(0, p._first, p._last, p._age);
}
string _first;
string _last;
int _age;
};
```
- Inject a specialization of `std::hash` for the class into the "std" namespace. We provide a convenient and small header `phmap_utils.h` which allows to easily add such specializations.
For example:
### file "Person.h"
```c++
#include <parallel_hashmap/phmap_utils.h> // minimal header providing phmap::HashState()
#include <string>
using std::string;
struct Person
{
bool operator==(const Person &o) const
{
return _first == o._first && _last == o._last && _age == o._age;
}
string _first;
string _last;
int _age;
};
namespace std
{
// inject specialization of std::hash for Person into namespace std
// ----------------------------------------------------------------
template<> struct hash<Person>
{
std::size_t operator()(Person const &p) const
{
return phmap::HashState().combine(0, p._first, p._last, p._age);
}
};
}
```
The `std::hash` specialization for `Person` combines the hash values for both first and last name and age, using the convenient phmap::HashState() function, and returns the combined hash value.
### file "main.cpp"
```c++
#include "Person.h" // defines Person with std::hash specialization
#include <iostream>
#include <parallel_hashmap/phmap.h>
int main()
{
// As we have defined a specialization of std::hash() for Person,
// we can now create sparse_hash_set or sparse_hash_map of Persons
// ----------------------------------------------------------------
phmap::flat_hash_set<Person> persons =
{ { "John", "Mitchell", 35 },
{ "Jane", "Smith", 32 },
{ "Jane", "Smith", 30 },
};
for (auto& p: persons)
std::cout << p._first << ' ' << p._last << " (" << p._age << ")" << '\n';
}
```
## Thread safety
Parallel Hashmap containers follow the thread safety rules of the Standard C++ library. In Particular:
- A single phmap hash table is thread safe for reading from multiple threads. For example, given a hash table A, it is safe to read A from thread 1 and from thread 2 simultaneously.
- If a single hash table is being written to by one thread, then all reads and writes to that hash table on the same or other threads must be protected. For example, given a hash table A, if thread 1 is writing to A, then thread 2 must be prevented from reading from or writing to A.
- It is safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given hash tables A and B of the same type, it is safe if A is being written in thread 1 and B is being read in thread 2.
- The *parallel* tables can be made internally thread-safe for concurrent read and write access, by providing a synchronization type (for example [std::mutex](https://en.cppreference.com/w/cpp/thread/mutex)) as the last template argument. Because locking is performed at the *submap* level, a high level of concurrency can still be achieved. Read access can be done safely using `if_contains()`, which passes a reference value to the callback while holding the *submap* lock. Similarly, write access can be done safely using `modify_if`, `try_emplace_l` or `lazy_emplace_l`. However, please be aware that iterators or references returned by standard APIs are not protected by the mutex, so they cannot be used reliably on a hash map which can be changed by another thread.
- Examples on how to use various mutex types, including boost::mutex, boost::shared_mutex and absl::Mutex can be found in `examples/bench.cc`
## Using the Parallel Hashmap from languages other than C++
While C++ is the native language of the Parallel Hashmap, we welcome bindings making it available for other languages. One such implementation has been created for Python and is described below:
- [GetPy - A Simple, Fast, and Small Hash Map for Python](https://github.com/atom-moyer/getpy): GetPy is a thin and robust binding to The Parallel Hashmap (https://github.com/greg7mdp/parallel-hashmap.git) which is the current state of the art for minimal memory overhead and fast runtime speed. The binding layer is supported by PyBind11 (https://github.com/pybind/pybind11.git) which is fast to compile and simple to extend. Serialization is handled by Cereal (https://github.com/USCiLab/cereal.git) which supports streaming binary serialization, a critical feature for the large hash maps this package is designed to support.
## Acknowledgements
Many thanks to the Abseil developers for implementing the swiss table and btree data structures (see [abseil-cpp](https://github.com/abseil/abseil-cpp)) upon which this work is based, and to Google for releasing it as open-source.
# parallel-hashmap
How to run these benchmarks
===========================
These bencharks were run on windows using Visual Studio 2017, in a cygwin window with the VC++ 2017 compiler env vars (add something like this in your Cygwin.bat:
CALL "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"
Running them on linux would require Makefile changes.
To build and run the tests, just update the path to the abseil libraries in the makefile, and run make.
Your charts are now in charts.html.
CXX=CL -EHsc -DNDEBUG -Fo$@ -O2
#CXX=CL -EHsc -g -debug -Zi -Fo$@
#CXX=g++ -ggdb -O2 -lm -std=c++11 -DNDEBUG
ABSEIL_LIBS=absl_bad_optional_access.lib absl_bad_variant_access.lib absl_base.lib absl_demangle_internal.lib absl_hash.lib absl_int128.lib absl_internal_bad_any_cast_impl.lib absl_internal_city.lib absl_internal_civil_time.lib absl_internal_debugging_internal.lib absl_internal_graphcycles_internal.lib absl_internal_hashtablez_sampler.lib absl_internal_malloc_internal.lib absl_internal_spinlock_wait.lib absl_internal_strings_internal.lib absl_internal_throw_delegate.lib absl_internal_time_zone.lib absl_optional.lib absl_raw_hash_set.lib absl_stacktrace.lib absl_strings.lib absl_symbolize.lib absl_synchronization.lib absl_time.lib
PROGS = stl_unordered_map sparsepp phmap abseil_flat abseil_parallel_flat phmap_flat
BUILD_PROGS = $(addprefix build/,$(PROGS))
SIZE = 100000000
ABSEIL = ../../abseil-cpp
PHMAP_SRC = ../parallel_hashmap
all: test
builddir:
@if [ ! -d build ]; then mkdir build; fi
build/stl_unordered_map: bench.cc Makefile
$(CXX) -DSTL_UNORDERED -I.. bench.cc -o $@
build/sparsepp: bench.cc Makefile
$(CXX) -DSPARSEPP -I.. -I../../sparsepp bench.cc -o $@
build/phmap: bench.cc Makefile $(PHMAP_SRC)/phmap.h
$(CXX) -DPHMAP -I.. -I$(ABSEIL) bench.cc /MD -o $@ /link /LIBPATH:$(ABSEIL)/build/lib ${ABSEIL_LIBS}
build/phmap_flat: bench.cc Makefile $(PHMAP_SRC)/phmap.h
$(CXX) -DPHMAP_FLAT -I.. bench.cc /MD -o $@
build/abseil_flat: bench.cc Makefile
$(CXX) -DABSEIL_FLAT -I.. -I$(ABSEIL) bench.cc /MD -o $@ /link /LIBPATH:$(ABSEIL)/build/lib ${ABSEIL_LIBS}
build/abseil_parallel_flat: bench.cc Makefile
$(CXX) -DABSEIL_PARALLEL_FLAT -I.. -I $(ABSEIL) bench.cc /MD -o $@ /link /LIBPATH:$(ABSEIL)/build/lib ${ABSEIL_LIBS}
build/emplace: emplace.cc Makefile $(PHMAP_SRC)/phmap.h
$(CXX) -DABSEIL_FLAT -I.. -I$(ABSEIL) emplace.cc /MD -o $@ /link /LIBPATH:$(ABSEIL)/build/lib ${ABSEIL_LIBS}
progs: $(BUILD_PROGS)
test: builddir progs
-rm -f output
#./build/stl_unordered_map $(SIZE) random >> output
#./build/sparsepp $(SIZE) random >> output
./build/abseil_flat $(SIZE) random >> output
#./build/phmap_flat $(SIZE) random >> output
./build/phmap $(SIZE) random >> output
./build/abseil_parallel_flat $(SIZE) random >> output
python make_chart_data.py < output
test_cust:
-rm -f output
#./build/abseil_flat $(SIZE) random >> output
#./build/sparsepp $(SIZE) random >> output
./build/abseil_parallel_flat_5 $(SIZE) random >> output
./build/abseil_parallel_flat $(SIZE) random >> output
python make_chart_data.py < output
chart:
python make_chart_data.py < output
clean:
-rm -fr output build
#include <inttypes.h>
#ifdef STL_UNORDERED
#include <unordered_map>
#define MAPNAME std::unordered_map
#define EXTRAARGS
#elif defined(SPARSEPP)
#define SPP_USE_SPP_ALLOC 1
#include <sparsepp/spp.h>
#define MAPNAME spp::sparse_hash_map
#define EXTRAARGS
#elif defined(ABSEIL_FLAT)
#include "absl/container/flat_hash_map.h"
#define MAPNAME absl::flat_hash_map
#define EXTRAARGS
#elif defined(PHMAP_FLAT)
#include "parallel_hashmap/phmap.h"
#define MAPNAME phmap::flat_hash_map
#define NMSP phmap
#define EXTRAARGS
#elif defined(ABSEIL_PARALLEL_FLAT) || defined(PHMAP)
#if defined(ABSEIL_PARALLEL_FLAT)
#include "absl/container/parallel_flat_hash_map.h"
#define MAPNAME absl::parallel_flat_hash_map
#define NMSP absl
#define MTX absl::Mutex
#else
#if 1
// use Abseil's mutex... faster
#include "absl/synchronization/mutex.h"
#define MTX absl::Mutex
#else
#include <mutex>
#define MTX std::mutex
#endif
#include "parallel_hashmap/phmap.h"
#define MAPNAME phmap::parallel_flat_hash_map
#define NMSP phmap
#endif
#define MT_SUPPORT 2
#if MT_SUPPORT == 1
// create the parallel_flat_hash_map without internal mutexes, for when
// we programatically ensure that each thread uses different internal submaps
// --------------------------------------------------------------------------
#define EXTRAARGS , NMSP::priv::hash_default_hash<K>, \
NMSP::priv::hash_default_eq<K>, \
std::allocator<std::pair<const K, V>>, 4, NMSP::NullMutex
#elif MT_SUPPORT == 2
// create the parallel_flat_hash_map with internal mutexes, for when
// we read/write the same parallel_flat_hash_map from multiple threads,
// without any special precautions.
// --------------------------------------------------------------------------
#define EXTRAARGS , NMSP::priv::hash_default_hash<K>, \
NMSP::priv::hash_default_eq<K>, \
std::allocator<std::pair<const K, V>>, 4, MTX
#else
#define EXTRAARGS
#endif
#endif
#define xstr(s) str(s)
#define str(s) #s
template <class K, class V>
using HashT = MAPNAME<K, V EXTRAARGS>;
using hash_t = HashT<int64_t, int64_t>;
using str_hash_t = HashT<const char *, int64_t>;
const char *program_slug = xstr(MAPNAME); // "_4";
#include <cassert>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <thread>
#include <chrono>
#include <ostream>
#include "parallel_hashmap/meminfo.h"
#include <vector>
using std::vector;
int64_t _abs(int64_t x) { return (x < 0) ? -x : x; }
// --------------------------------------------------------------------------
class Timer
{
typedef std::chrono::high_resolution_clock high_resolution_clock;
typedef std::chrono::milliseconds milliseconds;
public:
explicit Timer(bool run = false) { if (run) reset(); }
void reset() { _start = high_resolution_clock::now(); }
milliseconds elapsed() const
{
return std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - _start);
}
private:
high_resolution_clock::time_point _start;
};
// --------------------------------------------------------------------------
// from: https://github.com/preshing/RandomSequence
// --------------------------------------------------------------------------
class RSU
{
private:
unsigned int m_index;
unsigned int m_intermediateOffset;
static unsigned int permuteQPR(unsigned int x)
{
static const unsigned int prime = 4294967291u;
if (x >= prime)
return x; // The 5 integers out of range are mapped to themselves.
unsigned int residue = ((unsigned long long) x * x) % prime;
return (x <= prime / 2) ? residue : prime - residue;
}
public:
RSU(unsigned int seedBase, unsigned int seedOffset)
{
m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161);
m_intermediateOffset = permuteQPR(permuteQPR(seedOffset) + 0x46790905);
}
unsigned int next()
{
return permuteQPR((permuteQPR(m_index++) + m_intermediateOffset) ^ 0x5bf03635);
}
};
// --------------------------------------------------------------------------
char * new_string_from_integer(int num)
{
int ndigits = num == 0 ? 1 : (int)log10(num) + 1;
char * str = (char *)malloc(ndigits + 1);
sprintf(str, "%d", num);
return str;
}
// --------------------------------------------------------------------------
template <class T>
void _fill(vector<T> &v)
{
srand(1); // for a fair/deterministic comparison
for (size_t i = 0, sz = v.size(); i < sz; ++i)
v[i] = (T)(i * 10 + rand() % 10);
}
// --------------------------------------------------------------------------
template <class T>
void _shuffle(vector<T> &v)
{
for (size_t n = v.size(); n >= 2; --n)
std::swap(v[n - 1], v[static_cast<unsigned>(rand()) % n]);
}
// --------------------------------------------------------------------------
template <class T, class HT>
Timer _fill_random(vector<T> &v, HT &hash)
{
_fill<T>(v);
_shuffle<T>(v);
Timer timer(true);
for (size_t i = 0, sz = v.size(); i < sz; ++i)
hash.insert(typename HT::value_type(v[i], 0));
return timer;
}
// --------------------------------------------------------------------------
void out(const char* test, int64_t cnt, const Timer &t)
{
printf("%s,time,%lld,%s,%f\n", test, cnt, program_slug, (float)((double)t.elapsed().count() / 1000));
}
// --------------------------------------------------------------------------
void outmem(const char* test, int64_t cnt, uint64_t mem)
{
printf("%s,memory,%lld,%s,%lld\n", test, cnt, program_slug, mem);
}
static bool all_done = false;
static int64_t num_keys[16] = { 0 };
static int64_t loop_idx = 0;
static int64_t inner_cnt = 0;
static const char *test = "random";
// --------------------------------------------------------------------------
template <class HT>
void _fill_random_inner(int64_t cnt, HT &hash, RSU &rsu)
{
for (int64_t i=0; i<cnt; ++i)
{
hash.insert(typename HT::value_type(rsu.next(), 0));
++num_keys[0];
}
}
// --------------------------------------------------------------------------
template <class HT>
void _fill_random_inner_mt(int64_t cnt, HT &hash, RSU &rsu)
{
constexpr int64_t num_threads = 8; // has to be a power of two
std::unique_ptr<std::thread> threads[num_threads];
auto thread_fn = [&hash, cnt, num_threads](int64_t thread_idx, RSU rsu) {
#if MT_SUPPORT
size_t modulo = hash.subcnt() / num_threads; // subcnt() returns the number of submaps
for (int64_t i=0; i<cnt; ++i) // iterate over all values
{
unsigned int key = rsu.next(); // get next key to insert
#if MT_SUPPORT == 1
size_t hashval = hash.hash(key); // compute its hash
size_t idx = hash.subidx(hashval); // compute the submap index for this hash
if (idx / modulo == thread_idx) // if the submap is suitable for this thread
#elif MT_SUPPORT == 2
if (i % num_threads == thread_idx)
#endif
{
hash.insert(typename HT::value_type(key, 0)); // insert the value
++(num_keys[thread_idx]); // increment count of inserted values
}
}
#endif
};
// create and start 8 threads - each will insert in their own submaps
// thread 0 will insert the keys whose hash direct them to submap0 or submap1
// thread 1 will insert the keys whose hash direct them to submap2 or submap3
// --------------------------------------------------------------------------
for (int64_t i=0; i<num_threads; ++i)
threads[i].reset(new std::thread(thread_fn, i, rsu));
// rsu passed by value to threads... we need to increment the reference object
for (int64_t i=0; i<cnt; ++i)
rsu.next();
// wait for the threads to finish their work and exit
for (int64_t i=0; i<num_threads; ++i)
threads[i]->join();
}
// --------------------------------------------------------------------------
size_t total_num_keys()
{
size_t n = 0;
for (int i=0; i<16; ++i)
n += num_keys[i];
return n;
}
// --------------------------------------------------------------------------
template <class HT>
Timer _fill_random2(int64_t cnt, HT &hash)
{
test = "random";
unsigned int seed = 76687;
RSU rsu(seed, seed + 1);
Timer timer(true);
const int64_t num_loops = 10;
inner_cnt = cnt / num_loops;
for (int i=0; i<16; ++i)
num_keys[i] = 0;
for (loop_idx=0; loop_idx<num_loops; ++loop_idx)
{
#if 1 && MT_SUPPORT
// multithreaded insert
_fill_random_inner_mt(inner_cnt, hash, rsu);
#else
_fill_random_inner(inner_cnt, hash, rsu);
#endif
out(test, total_num_keys(), timer);
}
fprintf(stderr, "inserted %.2lfM\n", (double)hash.size() / 1000000);
return timer;
}
// --------------------------------------------------------------------------
template <class T, class HT>
Timer _lookup(vector<T> &v, HT &hash, size_t &num_present)
{
_fill_random(v, hash);
num_present = 0;
size_t max_val = v.size() * 10;
Timer timer(true);
for (size_t i = 0, sz = v.size(); i < sz; ++i)
{
num_present += (size_t)(hash.find(v[i]) != hash.end());
num_present += (size_t)(hash.find((T)(rand() % max_val)) != hash.end());
}
return timer;
}
// --------------------------------------------------------------------------
template <class T, class HT>
Timer _delete(vector<T> &v, HT &hash)
{
_fill_random(v, hash);
_shuffle(v); // don't delete in insertion order
Timer timer(true);
for(size_t i = 0, sz = v.size(); i < sz; ++i)
hash.erase(v[i]);
return timer;
}
// --------------------------------------------------------------------------
void memlog()
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
uint64_t nbytes_old_out = spp::GetProcessMemoryUsed();
uint64_t nbytes_old = spp::GetProcessMemoryUsed(); // last non outputted mem measurement
outmem(test, 0, nbytes_old);
int64_t last_loop = 0;
while (!all_done)
{
uint64_t nbytes = spp::GetProcessMemoryUsed();
if ((double)_abs(nbytes - nbytes_old_out) / nbytes_old_out > 0.03 ||
(double)_abs(nbytes - nbytes_old) / nbytes_old > 0.01)
{
if ((double)(nbytes - nbytes_old) / nbytes_old > 0.03)
outmem(test, total_num_keys() - 1, nbytes_old);
outmem(test, total_num_keys(), nbytes);
nbytes_old_out = nbytes;
last_loop = loop_idx;
}
else if (loop_idx > last_loop)
{
outmem(test, total_num_keys(), nbytes);
nbytes_old_out = nbytes;
last_loop = loop_idx;
}
nbytes_old = nbytes;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
// --------------------------------------------------------------------------
int main(int argc, char ** argv)
{
int64_t i, value = 0;
if(argc <= 2)
return 1;
int64_t num_keys = atoi(argv[1]);
hash_t hash;
str_hash_t str_hash;
srand(1); // for a fair/deterministic comparison
Timer timer(true);
#if MT_SUPPORT
if (!strcmp(program_slug,"absl::parallel_flat_hash_map") ||
!strcmp(program_slug,"phmap::parallel_flat_hash_map"))
program_slug = xstr(MAPNAME) "_mt";
#endif
std::thread t1(memlog);
try
{
if(!strcmp(argv[2], "sequential"))
{
for(i = 0; i < num_keys; i++)
hash.insert(hash_t::value_type(i, value));
}
#if 0
else if(!strcmp(argv[2], "random"))
{
vector<int64_t> v(num_keys);
timer = _fill_random(v, hash);
out("random", num_keys, timer);
}
#endif
else if(!strcmp(argv[2], "random"))
{
fprintf(stderr, "size = %d\n", sizeof(hash));
timer = _fill_random2(num_keys, hash);
//out("random", num_keys, timer);
//fprintf(stderr, "inserted %llu\n", hash.size());
}
else if(!strcmp(argv[2], "lookup"))
{
vector<int64_t> v(num_keys);
size_t num_present;
timer = _lookup(v, hash, num_present);
//fprintf(stderr, "found %llu\n", num_present);
}
else if(!strcmp(argv[2], "delete"))
{
vector<int64_t> v(num_keys);
timer = _delete(v, hash);
}
else if(!strcmp(argv[2], "sequentialstring"))
{
for(i = 0; i < num_keys; i++)
str_hash.insert(str_hash_t::value_type(new_string_from_integer(i), value));
}
else if(!strcmp(argv[2], "randomstring"))
{
for(i = 0; i < num_keys; i++)
str_hash.insert(str_hash_t::value_type(new_string_from_integer((int)rand()), value));
}
else if(!strcmp(argv[2], "deletestring"))
{
for(i = 0; i < num_keys; i++)
str_hash.insert(str_hash_t::value_type(new_string_from_integer(i), value));
timer.reset();
for(i = 0; i < num_keys; i++)
str_hash.erase(new_string_from_integer(i));
}
//printf("%f\n", (float)((double)timer.elapsed().count() / 1000));
fflush(stdout);
//std::this_thread::sleep_for(std::chrono::seconds(1000));
}
catch (...)
{
}
all_done = true;
t1.join();
return 0;
}
import sys, os, subprocess, signal
programs = [
'stl_unordered_map',
'abseil_flat',
'abseil_parallel_flat'
]
test_size = 1
minkeys = 0
maxkeys = 1000
interval = 100
best_out_of = 1
if test_size == 2:
multiplier = 1000 * 1000
maxkeys = 500
best_out_of = 3
elif test_size == 1:
multiplier = 100 * 1000
interval = 200
else:
multiplier = 10 * 1000
# and use nice/ionice
# and shut down to the console
# and swapoff any swap files/partitions
outfile = open('output', 'w')
if len(sys.argv) > 1:
benchtypes = sys.argv[1:]
else:
benchtypes = ( 'random', 'lookup', 'delete',)
#benchtypes = ( 'lookup', )
for benchtype in benchtypes:
nkeys = minkeys * multiplier
while nkeys <= (maxkeys * multiplier):
for program in programs:
fastest_attempt = 1000000
fastest_attempt_data = ''
for attempt in range(best_out_of):
proc = subprocess.Popen(['./build/'+program, str(nkeys), benchtype], stdout=subprocess.PIPE)
# wait for the program to fill up memory and spit out its "ready" message
try:
runtime = float(proc.stdout.readline().strip())
except:
runtime = 0
ps_proc = subprocess.Popen(['ps up %d | tail -n1' % proc.pid], shell=True, stdout=subprocess.PIPE)
#nbytes = int(ps_proc.stdout.read().split()[4]) * 1024
#ps_proc.wait()
nbytes = 1000000
os.kill(proc.pid, signal.SIGKILL)
proc.wait()
if nbytes and runtime: # otherwise it crashed
line = ','.join(map(str, [benchtype, nkeys, program, nbytes, "%0.6f" % runtime]))
if runtime < fastest_attempt:
fastest_attempt = runtime
fastest_attempt_data = line
if fastest_attempt != 1000000:
print >> outfile, fastest_attempt_data
print fastest_attempt_data
nkeys += interval * multiplier
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hash Table Benchmarks</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="./style.css" />
<link href="./js/examples.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="./js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.mousewheel.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.canvaswrapper.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.colorhelpers.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.saturated.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.browser.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.drawSeries.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.errorbars.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.uiConstants.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.logaxis.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.symbol.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.flatdata.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.navigate.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.fillbetween.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.stack.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.touchNavigate.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.hover.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.touch.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.time.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.axislabels.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.selection.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.composeImages.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.flot.legend.js"></script>
<script type="text/javascript">
series_settings = {
lines: { show: true, lineWidth: 2 },
points: { show: true, radius: 2 }
};
grid_settings = { tickColor: '#ddd' };
divider = 10
xaxis_settings = {
tickSize: 200000000 / divider, <!-- 200000000 -->
tickFormatter: function(num, obj) { return parseInt(num/1000000) + 'M'; }
};
yaxis_runtime_settings = {
labelWidth: 60,
tickFormatter: function(num, obj) { return num + ' sec.'; }
};
yaxis_memory_settings = {
labelWidth: 60,
tickSize: 10*1024*1024*1024 / divider, <!-- 1024 -->
tickFormatter: function(num, obj) { return parseInt(num/1024/1024) + 'MB'; }
};
legend_settings = {
position: 'nw',
show: true,
backgroundOpacity: 0
};
runtime_settings = {
series: series_settings,
grid: grid_settings,
xaxis: xaxis_settings,
yaxis: yaxis_runtime_settings,
legend: legend_settings,
zoom: { interactive: true },
pan: { interactive: true }
};
memory_settings = {
series: series_settings,
grid: grid_settings,
xaxis: xaxis_settings,
yaxis: yaxis_memory_settings,
legend: legend_settings,
zoom: { interactive: true },
pan: { interactive: true }
};
__CHART_DATA_GOES_HERE__
$(function () {
__PLOT_SPEC_GOES_HERE__
});
</script>
</head>
<body>
<style>
body, * { font-family: sans-serif; }
div.table-title {
width: 700px;
text-indent: 75px;
text-decoration-line: underline;
text-decoration-style: solid;
font-style: normal;
font-size: 0.9em;
color: #222;
margin-top: 25px;
margin-left: 25px;
}
div.chart {
width: 800px;
height: 300px;
font-style: normal;
font-size: 0.75em;
margin-left: 25px;
}
div.xaxis-title {
width: 700px;
text-align: center;
text-decoration-line: underline;
text-decoration-style: solid;
font-style: italic;
font-size: 0.85em;
color: #666;
margin-top: 10px;
margin-bottom: 50px;
margin-left: 25px;
}
</style>
__PLOT_DIV_SPEC_GOES_HERE__
</body>
</html>
* { padding: 0; margin: 0; vertical-align: top; }
body {
background: url(background.png) repeat-x;
font: 18px "proxima-nova", Helvetica, Arial, sans-serif;
line-height: 1.5;
}
a { color: #069; }
a:hover { color: #28b; }
h2 {
margin-top: 15px;
font: normal 32px "omnes-pro", Helvetica, Arial, sans-serif;
}
h3 {
margin-left: 30px;
font: normal 26px "omnes-pro", Helvetica, Arial, sans-serif;
color: #666;
}
p {
margin-top: 10px;
}
button {
font-size: 18px;
padding: 1px 7px;
}
input {
font-size: 18px;
}
input[type=checkbox] {
margin: 7px;
}
#header {
position: relative;
width: 900px;
margin: auto;
}
#header h2 {
margin-left: 10px;
vertical-align: middle;
font-size: 42px;
font-weight: bold;
text-decoration: none;
color: #000;
}
#content {
width: 880px;
margin: 0 auto;
padding: 10px;
}
#footer {
margin-top: 25px;
margin-bottom: 10px;
text-align: center;
font-size: 12px;
color: #999;
}
.demo-container {
box-sizing: border-box;
width: 850px;
height: 450px;
padding: 20px 15px 15px 15px;
margin: 15px auto 30px auto;
border: 1px solid #ddd;
background: #fff;
background: linear-gradient(#f6f6f6 0, #fff 50px);
background: -o-linear-gradient(#f6f6f6 0, #fff 50px);
background: -ms-linear-gradient(#f6f6f6 0, #fff 50px);
background: -moz-linear-gradient(#f6f6f6 0, #fff 50px);
background: -webkit-linear-gradient(#f6f6f6 0, #fff 50px);
box-shadow: 0 3px 10px rgba(0,0,0,0.15);
-o-box-shadow: 0 3px 10px rgba(0,0,0,0.1);
-ms-box-shadow: 0 3px 10px rgba(0,0,0,0.1);
-moz-box-shadow: 0 3px 10px rgba(0,0,0,0.1);
-webkit-box-shadow: 0 3px 10px rgba(0,0,0,0.1);
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.demo-placeholder {
width: 100%;
height: 100%;
font-size: 14px;
}
fieldset {
display: block;
-webkit-margin-start: 2px;
-webkit-margin-end: 2px;
-webkit-padding-before: 0.35em;
-webkit-padding-start: 0.75em;
-webkit-padding-end: 0.75em;
-webkit-padding-after: 0.625em;
min-width: -webkit-min-content;
border-width: 2px;
border-style: groove;
border-color: threedface;
border-image: initial;
padding: 10px;
}
.legend {
display: block;
-webkit-padding-start: 2px;
-webkit-padding-end: 2px;
border-width: initial;
border-style: none;
border-color: initial;
border-image: initial;
padding-left: 10px;
padding-right: 10px;
padding-top: 10px;
padding-bottom: 10px;
}
.legendLayer .background {
fill: rgba(255, 255, 255, 0.85);
stroke: rgba(0, 0, 0, 0.85);
stroke-width: 1;
}
input[type="radio"] {
margin-top: -1px;
vertical-align: middle;
}
.tickLabel {
line-height: 1.1;
}
/** ## jquery.flot.canvaswrapper
This plugin contains the function for creating and manipulating both the canvas
layers and svg layers.
The Canvas object is a wrapper around an HTML5 canvas tag.
The constructor Canvas(cls, container) takes as parameters cls,
the list of classes to apply to the canvas adnd the containter,
element onto which to append the canvas. The canvas operations
don't work unless the canvas is attached to the DOM.
### jquery.canvaswrapper.js API functions
*/
(function($) {
var Canvas = function(cls, container) {
var element = container.getElementsByClassName(cls)[0];
if (!element) {
element = document.createElement('canvas');
element.className = cls;
element.style.direction = 'ltr';
element.style.position = 'absolute';
element.style.left = '0px';
element.style.top = '0px';
container.appendChild(element);
// If HTML5 Canvas isn't available, throw
if (!element.getContext) {
throw new Error('Canvas is not available.');
}
}
this.element = element;
var context = this.context = element.getContext('2d');
this.pixelRatio = $.plot.browser.getPixelRatio(context);
// Size the canvas to match the internal dimensions of its container
var box = container.getBoundingClientRect();
this.resize(box.width, box.height);
// Collection of HTML div layers for text overlaid onto the canvas
this.SVGContainer = null;
this.SVG = {};
// Cache of text fragments and metrics, so we can avoid expensively
// re-calculating them when the plot is re-rendered in a loop.
this._textCache = {};
}
/**
- resize(width, height)
Resizes the canvas to the given dimensions.
The width represents the new width of the canvas, meanwhile the height
is the new height of the canvas, both of them in pixels.
*/
Canvas.prototype.resize = function(width, height) {
var minSize = 10;
width = width < minSize ? minSize : width;
height = height < minSize ? minSize : height;
var element = this.element,
context = this.context,
pixelRatio = this.pixelRatio;
// Resize the canvas, increasing its density based on the display's
// pixel ratio; basically giving it more pixels without increasing the
// size of its element, to take advantage of the fact that retina
// displays have that many more pixels in the same advertised space.
// Resizing should reset the state (excanvas seems to be buggy though)
if (this.width !== width) {
element.width = width * pixelRatio;
element.style.width = width + 'px';
this.width = width;
}
if (this.height !== height) {
element.height = height * pixelRatio;
element.style.height = height + 'px';
this.height = height;
}
// Save the context, so we can reset in case we get replotted. The
// restore ensure that we're really back at the initial state, and
// should be safe even if we haven't saved the initial state yet.
context.restore();
context.save();
// Scale the coordinate space to match the display density; so even though we
// may have twice as many pixels, we still want lines and other drawing to
// appear at the same size; the extra pixels will just make them crisper.
context.scale(pixelRatio, pixelRatio);
};
/**
- clear()
Clears the entire canvas area, not including any overlaid HTML text
*/
Canvas.prototype.clear = function() {
this.context.clearRect(0, 0, this.width, this.height);
};
/**
- render()
Finishes rendering the canvas, including managing the text overlay.
*/
Canvas.prototype.render = function() {
var cache = this._textCache;
// For each text layer, add elements marked as active that haven't
// already been rendered, and remove those that are no longer active.
for (var layerKey in cache) {
if (hasOwnProperty.call(cache, layerKey)) {
var layer = this.getSVGLayer(layerKey),
layerCache = cache[layerKey];
var display = layer.style.display;
layer.style.display = 'none';
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var val = styleCache[key],
positions = val.positions;
for (var i = 0, position; positions[i]; i++) {
position = positions[i];
if (position.active) {
if (!position.rendered) {
layer.appendChild(position.element);
position.rendered = true;
}
} else {
positions.splice(i--, 1);
if (position.rendered) {
while (position.element.firstChild) {
position.element.removeChild(position.element.firstChild);
}
position.element.parentNode.removeChild(position.element);
}
}
}
if (positions.length === 0) {
if (val.measured) {
val.measured = false;
} else {
delete styleCache[key];
}
}
}
}
}
}
layer.style.display = display;
}
}
};
/**
- getSVGLayer(classes)
Creates (if necessary) and returns the SVG overlay container.
The classes string represents the string of space-separated CSS classes
used to uniquely identify the text layer. It return the svg-layer div.
*/
Canvas.prototype.getSVGLayer = function(classes) {
var layer = this.SVG[classes];
// Create the SVG layer if it doesn't exist
if (!layer) {
// Create the svg layer container, if it doesn't exist
var svgElement;
if (!this.SVGContainer) {
this.SVGContainer = document.createElement('div');
this.SVGContainer.className = 'flot-svg';
this.SVGContainer.style.position = 'absolute';
this.SVGContainer.style.top = '0px';
this.SVGContainer.style.left = '0px';
this.SVGContainer.style.bottom = '0px';
this.SVGContainer.style.right = '0px';
this.SVGContainer.style.pointerEvents = 'none';
this.element.parentNode.appendChild(this.SVGContainer);
svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElement.style.width = '100%';
svgElement.style.height = '100%';
this.SVGContainer.appendChild(svgElement);
} else {
svgElement = this.SVGContainer.firstChild;
}
layer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
layer.setAttribute('class', classes);
layer.style.position = 'absolute';
layer.style.top = '0px';
layer.style.left = '0px';
layer.style.bottom = '0px';
layer.style.right = '0px';
svgElement.appendChild(layer);
this.SVG[classes] = layer;
}
return layer;
};
/**
- getTextInfo(layer, text, font, angle, width)
Creates (if necessary) and returns a text info object.
The object looks like this:
```js
{
width //Width of the text's wrapper div.
height //Height of the text's wrapper div.
element //The HTML div containing the text.
positions //Array of positions at which this text is drawn.
}
```
The positions array contains objects that look like this:
```js
{
active //Flag indicating whether the text should be visible.
rendered //Flag indicating whether the text is currently visible.
element //The HTML div containing the text.
text //The actual text and is identical with element[0].textContent.
x //X coordinate at which to draw the text.
y //Y coordinate at which to draw the text.
}
```
Each position after the first receives a clone of the original element.
The idea is that that the width, height, and general 'identity' of the
text is constant no matter where it is placed; the placements are a
secondary property.
Canvas maintains a cache of recently-used text info objects; getTextInfo
either returns the cached element or creates a new entry.
The layer parameter is string of space-separated CSS classes uniquely
identifying the layer containing this text.
Text is the text string to retrieve info for.
Font is either a string of space-separated CSS classes or a font-spec object,
defining the text's font and style.
Angle is the angle at which to rotate the text, in degrees. Angle is currently unused,
it will be implemented in the future.
The last parameter is the Maximum width of the text before it wraps.
The method returns a text info object.
*/
Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
var textStyle, layerCache, styleCache, info;
// Cast the value to a string, in case we were given a number or such
text = '' + text;
// If the font is a font-spec object, generate a CSS font definition
if (typeof font === 'object') {
textStyle = font.style + ' ' + font.variant + ' ' + font.weight + ' ' + font.size + 'px/' + font.lineHeight + 'px ' + font.family;
} else {
textStyle = font;
}
// Retrieve (or create) the cache for the text's layer and styles
layerCache = this._textCache[layer];
if (layerCache == null) {
layerCache = this._textCache[layer] = {};
}
styleCache = layerCache[textStyle];
if (styleCache == null) {
styleCache = layerCache[textStyle] = {};
}
var key = generateKey(text);
info = styleCache[key];
// If we can't find a matching element in our cache, create a new one
if (!info) {
var element = document.createElementNS('http://www.w3.org/2000/svg', 'text');
if (text.indexOf('<br>') !== -1) {
addTspanElements(text, element, -9999);
} else {
var textNode = document.createTextNode(text);
element.appendChild(textNode);
}
element.style.position = 'absolute';
element.style.maxWidth = width;
element.setAttributeNS(null, 'x', -9999);
element.setAttributeNS(null, 'y', -9999);
if (typeof font === 'object') {
element.style.font = textStyle;
element.style.fill = font.fill;
} else if (typeof font === 'string') {
element.setAttribute('class', font);
}
this.getSVGLayer(layer).appendChild(element);
var elementRect = element.getBBox();
info = styleCache[key] = {
width: elementRect.width,
height: elementRect.height,
measured: true,
element: element,
positions: []
};
//remove elements from dom
while (element.firstChild) {
element.removeChild(element.firstChild);
}
element.parentNode.removeChild(element);
}
info.measured = true;
return info;
};
/**
- addText (layer, x, y, text, font, angle, width, halign, valign, transforms)
Adds a text string to the canvas text overlay.
The text isn't drawn immediately; it is marked as rendering, which will
result in its addition to the canvas on the next render pass.
The layer is string of space-separated CSS classes uniquely
identifying the layer containing this text.
X and Y represents the X and Y coordinate at which to draw the text.
and text is the string to draw
*/
Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign, transforms) {
var info = this.getTextInfo(layer, text, font, angle, width),
positions = info.positions;
// Tweak the div's position to match the text's alignment
if (halign === 'center') {
x -= info.width / 2;
} else if (halign === 'right') {
x -= info.width;
}
if (valign === 'middle') {
y -= info.height / 2;
} else if (valign === 'bottom') {
y -= info.height;
}
y += 0.75 * info.height;
// Determine whether this text already exists at this position.
// If so, mark it for inclusion in the next render pass.
for (var i = 0, position; positions[i]; i++) {
position = positions[i];
if (position.x === x && position.y === y && position.text === text) {
position.active = true;
return;
} else if (position.active === false) {
position.active = true;
position.text = text;
if (text.indexOf('<br>') !== -1) {
y -= 0.25 * info.height;
addTspanElements(text, position.element, x);
} else {
position.element.textContent = text;
}
position.element.setAttributeNS(null, 'x', x);
position.element.setAttributeNS(null, 'y', y);
position.x = x;
position.y = y;
return;
}
}
// If the text doesn't exist at this position, create a new entry
// For the very first position we'll re-use the original element,
// while for subsequent ones we'll clone it.
position = {
active: true,
rendered: false,
element: positions.length ? info.element.cloneNode() : info.element,
text: text,
x: x,
y: y
};
positions.push(position);
if (text.indexOf('<br>') !== -1) {
y -= 0.25 * info.height;
addTspanElements(text, position.element, x);
} else {
position.element.textContent = text;
}
// Move the element to its final position within the container
position.element.setAttributeNS(null, 'x', x);
position.element.setAttributeNS(null, 'y', y);
position.element.style.textAlign = halign;
if (transforms) {
transforms.forEach(function(t) {
info.element.transform.baseVal.appendItem(t);
});
}
};
var addTspanElements = function(text, element, x) {
var lines = text.split('<br>'),
tspan, i, offset;
for (i = 0; i < lines.length; i++) {
if (!element.childNodes[i]) {
tspan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
element.appendChild(tspan);
} else {
tspan = element.childNodes[i];
}
tspan.textContent = lines[i];
offset = i * 1 + 'em';
tspan.setAttributeNS(null, 'dy', offset);
tspan.setAttributeNS(null, 'x', x);
}
}
/**
- removeText (layer, x, y, text, font, angle)
The function removes one or more text strings from the canvas text overlay.
If no parameters are given, all text within the layer is removed.
Note that the text is not immediately removed; it is simply marked as
inactive, which will result in its removal on the next render pass.
This avoids the performance penalty for 'clear and redraw' behavior,
where we potentially get rid of all text on a layer, but will likely
add back most or all of it later, as when redrawing axes, for example.
The layer is a string of space-separated CSS classes uniquely
identifying the layer containing this text. The following parameter are
X and Y coordinate of the text.
Text is the string to remove, while the font is either a string of space-separated CSS
classes or a font-spec object, defining the text's font and style.
*/
Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
var info, htmlYCoord;
if (text == null) {
var layerCache = this._textCache[layer];
if (layerCache != null) {
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var positions = styleCache[key].positions;
positions.forEach(function(position) {
position.active = false;
});
}
}
}
}
}
} else {
info = this.getTextInfo(layer, text, font, angle);
positions = info.positions;
positions.forEach(function(position) {
htmlYCoord = y + 0.75 * info.height;
if (position.x === x && position.y === htmlYCoord && position.text === text) {
position.active = false;
}
});
}
};
/**
- clearCache()
Clears the cache used to speed up the text size measurements.
As an (unfortunate) side effect all text within the text Layer is removed.
Use this function before plot.setupGrid() and plot.draw() if the plot just
became visible or the styles changed.
*/
Canvas.prototype.clearCache = function() {
var cache = this._textCache;
for (var layerKey in cache) {
if (hasOwnProperty.call(cache, layerKey)) {
var layer = this.getSVGLayer(layerKey);
while (layer.firstChild) {
layer.removeChild(layer.firstChild);
}
}
};
this._textCache = {};
};
function generateKey(text) {
return text.replace(/0|1|2|3|4|5|6|7|8|9/g, '0');
}
if (!window.Flot) {
window.Flot = {};
}
window.Flot.Canvas = Canvas;
})(jQuery);
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function($) {
$.color = {};
// construct color object with some convenient chainable helpers
$.color.make = function (r, g, b, a) {
var o = {};
o.r = r || 0;
o.g = g || 0;
o.b = b || 0;
o.a = a != null ? a : 1;
o.add = function (c, d) {
for (var i = 0; i < c.length; ++i) {
o[c.charAt(i)] += d;
}
return o.normalize();
};
o.scale = function (c, f) {
for (var i = 0; i < c.length; ++i) {
o[c.charAt(i)] *= f;
}
return o.normalize();
};
o.toString = function () {
if (o.a >= 1.0) {
return "rgb(" + [o.r, o.g, o.b].join(",") + ")";
} else {
return "rgba(" + [o.r, o.g, o.b, o.a].join(",") + ")";
}
};
o.normalize = function () {
function clamp(min, value, max) {
return value < min ? min : (value > max ? max : value);
}
o.r = clamp(0, parseInt(o.r), 255);
o.g = clamp(0, parseInt(o.g), 255);
o.b = clamp(0, parseInt(o.b), 255);
o.a = clamp(0, o.a, 1);
return o;
};
o.clone = function () {
return $.color.make(o.r, o.b, o.g, o.a);
};
return o.normalize();
}
// extract CSS color property from element, going up in the DOM
// if it's "transparent"
$.color.extract = function (elem, css) {
var c;
do {
c = elem.css(css).toLowerCase();
// keep going until we find an element that has color, or
// we hit the body or root (have no parent)
if (c !== '' && c !== 'transparent') {
break;
}
elem = elem.parent();
} while (elem.length && !$.nodeName(elem.get(0), "body"));
// catch Safari's way of signalling transparent
if (c === "rgba(0, 0, 0, 0)") {
c = "transparent";
}
return $.color.parse(c);
}
// parse CSS color string (like "rgb(10, 32, 43)" or "#fff"),
// returns color object, if parsing failed, you get black (0, 0,
// 0) out
$.color.parse = function (str) {
var res, m = $.color.make;
// Look for rgb(num,num,num)
res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str);
if (res) {
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));
}
// Look for rgba(num,num,num,num)
res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)
if (res) {
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));
}
// Look for rgb(num%,num%,num%)
res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)%\s*,\s*([0-9]+(?:\.[0-9]+)?)%\s*,\s*([0-9]+(?:\.[0-9]+)?)%\s*\)/.exec(str);
if (res) {
return m(parseFloat(res[1]) * 2.55, parseFloat(res[2]) * 2.55, parseFloat(res[3]) * 2.55);
}
// Look for rgba(num%,num%,num%,num)
res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)%\s*,\s*([0-9]+(?:\.[0-9]+)?)%\s*,\s*([0-9]+(?:\.[0-9]+)?)%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str);
if (res) {
return m(parseFloat(res[1]) * 2.55, parseFloat(res[2]) * 2.55, parseFloat(res[3]) * 2.55, parseFloat(res[4]));
}
// Look for #a0b1c2
res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str);
if (res) {
return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));
}
// Look for #fff
res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str);
if (res) {
return m(parseInt(res[1] + res[1], 16), parseInt(res[2] + res[2], 16), parseInt(res[3] + res[3], 16));
}
// Otherwise, we're most likely dealing with a named color
var name = $.trim(str).toLowerCase();
if (name === "transparent") {
return m(255, 255, 255, 0);
} else {
// default to black
res = lookupColors[name] || [0, 0, 0];
return m(res[0], res[1], res[2]);
}
}
var lookupColors = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0]
};
})(jQuery);
/*
Axis label plugin for flot
Derived from:
Axis Labels Plugin for flot.
http://github.com/markrcote/flot-axislabels
Original code is Copyright (c) 2010 Xuan Luo.
Original code was released under the GPLv3 license by Xuan Luo, September 2010.
Original code was rereleased under the MIT license by Xuan Luo, April 2012.
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($) {
"use strict";
var options = {
axisLabels: {
show: true
}
};
function AxisLabel(axisName, position, padding, placeholder, axisLabel, surface) {
this.axisName = axisName;
this.position = position;
this.padding = padding;
this.placeholder = placeholder;
this.axisLabel = axisLabel;
this.surface = surface;
this.width = 0;
this.height = 0;
this.elem = null;
}
AxisLabel.prototype.calculateSize = function() {
var axisId = this.axisName + 'Label',
layerId = axisId + 'Layer',
className = axisId + ' axisLabels';
var info = this.surface.getTextInfo(layerId, this.axisLabel, className);
this.labelWidth = info.width;
this.labelHeight = info.height;
if (this.position === 'left' || this.position === 'right') {
this.width = this.labelHeight + this.padding;
this.height = 0;
} else {
this.width = 0;
this.height = this.labelHeight + this.padding;
}
};
AxisLabel.prototype.transforms = function(degrees, x, y, svgLayer) {
var transforms = [], translate, rotate;
if (x !== 0 || y !== 0) {
translate = svgLayer.createSVGTransform();
translate.setTranslate(x, y);
transforms.push(translate);
}
if (degrees !== 0) {
rotate = svgLayer.createSVGTransform();
var centerX = Math.round(this.labelWidth / 2),
centerY = 0;
rotate.setRotate(degrees, centerX, centerY);
transforms.push(rotate);
}
return transforms;
};
AxisLabel.prototype.calculateOffsets = function(box) {
var offsets = {
x: 0,
y: 0,
degrees: 0
};
if (this.position === 'bottom') {
offsets.x = box.left + box.width / 2 - this.labelWidth / 2;
offsets.y = box.top + box.height - this.labelHeight;
} else if (this.position === 'top') {
offsets.x = box.left + box.width / 2 - this.labelWidth / 2;
offsets.y = box.top;
} else if (this.position === 'left') {
offsets.degrees = -90;
offsets.x = box.left - this.labelWidth / 2;
offsets.y = box.height / 2 + box.top;
} else if (this.position === 'right') {
offsets.degrees = 90;
offsets.x = box.left + box.width - this.labelWidth / 2;
offsets.y = box.height / 2 + box.top;
}
offsets.x = Math.round(offsets.x);
offsets.y = Math.round(offsets.y);
return offsets;
};
AxisLabel.prototype.cleanup = function() {
var axisId = this.axisName + 'Label',
layerId = axisId + 'Layer',
className = axisId + ' axisLabels';
this.surface.removeText(layerId, 0, 0, this.axisLabel, className);
};
AxisLabel.prototype.draw = function(box) {
var axisId = this.axisName + 'Label',
layerId = axisId + 'Layer',
className = axisId + ' axisLabels',
offsets = this.calculateOffsets(box),
style = {
position: 'absolute',
bottom: '',
right: '',
display: 'inline-block',
'white-space': 'nowrap'
};
var layer = this.surface.getSVGLayer(layerId);
var transforms = this.transforms(offsets.degrees, offsets.x, offsets.y, layer.parentNode);
this.surface.addText(layerId, 0, 0, this.axisLabel, className, undefined, undefined, undefined, undefined, transforms);
this.surface.render();
Object.keys(style).forEach(function(key) {
layer.style[key] = style[key];
});
};
function init(plot) {
plot.hooks.processOptions.push(function(plot, options) {
if (!options.axisLabels.show) {
return;
}
var axisLabels = {};
var defaultPadding = 2; // padding between axis and tick labels
plot.hooks.axisReserveSpace.push(function(plot, axis) {
var opts = axis.options;
var axisName = axis.direction + axis.n;
axis.labelHeight += axis.boxPosition.centerY;
axis.labelWidth += axis.boxPosition.centerX;
if (!opts || !opts.axisLabel || !axis.show) {
return;
}
var padding = opts.axisLabelPadding === undefined
? defaultPadding
: opts.axisLabelPadding;
var axisLabel = axisLabels[axisName];
if (!axisLabel) {
axisLabel = new AxisLabel(axisName,
opts.position, padding,
plot.getPlaceholder()[0], opts.axisLabel, plot.getSurface());
axisLabels[axisName] = axisLabel;
}
axisLabel.calculateSize();
// Incrementing the sizes of the tick labels.
axis.labelHeight += axisLabel.height;
axis.labelWidth += axisLabel.width;
});
// TODO - use the drawAxis hook
plot.hooks.draw.push(function(plot, ctx) {
$.each(plot.getAxes(), function(flotAxisName, axis) {
var opts = axis.options;
if (!opts || !opts.axisLabel || !axis.show) {
return;
}
var axisName = axis.direction + axis.n;
axisLabels[axisName].draw(axis.box);
});
});
plot.hooks.shutdown.push(function(plot, eventHolder) {
for (var axisName in axisLabels) {
axisLabels[axisName].cleanup();
}
});
});
};
$.plot.plugins.push({
init: init,
options: options,
name: 'axisLabels',
version: '3.0'
});
})(jQuery);
/** ## jquery.flot.browser.js
This plugin is used to make available some browser-related utility functions.
### Methods
*/
(function ($) {
'use strict';
var browser = {
/**
- getPageXY(e)
Calculates the pageX and pageY using the screenX, screenY properties of the event
and the scrolling of the page. This is needed because the pageX and pageY
properties of the event are not correct while running tests in Edge. */
getPageXY: function (e) {
// This code is inspired from https://stackoverflow.com/a/3464890
var doc = document.documentElement,
pageX = e.clientX + (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
pageY = e.clientY + (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
return { X: pageX, Y: pageY };
},
/**
- getPixelRatio(context)
This function returns the current pixel ratio defined by the product of desktop
zoom and page zoom.
Additional info: https://www.html5rocks.com/en/tutorials/canvas/hidpi/
*/
getPixelRatio: function(context) {
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio =
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return devicePixelRatio / backingStoreRatio;
},
/**
- isSafari, isMobileSafari, isOpera, isFirefox, isIE, isEdge, isChrome, isBlink
This is a collection of functions, used to check if the code is running in a
particular browser or Javascript engine.
*/
isSafari: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Safari 3.0+ "[object HTMLElementConstructor]"
return /constructor/i.test(window.top.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.top['safari'] || (typeof window.top.safari !== 'undefined' && window.top.safari.pushNotification));
},
isMobileSafari: function() {
//isMobileSafari adapted from https://stackoverflow.com/questions/3007480/determine-if-user-navigated-from-mobile-safari
return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/);
},
isOpera: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
//Opera 8.0+
return (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
},
isFirefox: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Firefox 1.0+
return typeof InstallTrigger !== 'undefined';
},
isIE: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Internet Explorer 6-11
return /*@cc_on!@*/false || !!document.documentMode;
},
isEdge: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Edge 20+
return !browser.isIE() && !!window.StyleMedia;
},
isChrome: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
// Chrome 1+
return !!window.chrome && !!window.chrome.webstore;
},
isBlink: function() {
// *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
return (browser.isChrome() || browser.isOpera()) && !!window.CSS;
}
};
$.plot.browser = browser;
})(jQuery);
/* Flot plugin for plotting textual data or categories.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Consider a dataset like [["February", 34], ["March", 20], ...]. This plugin
allows you to plot such a dataset directly.
To enable it, you must specify mode: "categories" on the axis with the textual
labels, e.g.
$.plot("#placeholder", data, { xaxis: { mode: "categories" } });
By default, the labels are ordered as they are met in the data series. If you
need a different ordering, you can specify "categories" on the axis options
and list the categories there:
xaxis: {
mode: "categories",
categories: ["February", "March", "April"]
}
If you need to customize the distances between the categories, you can specify
"categories" as an object mapping labels to values
xaxis: {
mode: "categories",
categories: { "February": 1, "March": 3, "April": 4 }
}
If you don't specify all categories, the remaining categories will be numbered
from the max value plus 1 (with a spacing of 1 between each).
Internally, the plugin works by transforming the input data through an auto-
generated mapping where the first category becomes 0, the second 1, etc.
Hence, a point like ["February", 34] becomes [0, 34] internally in Flot (this
is visible in hover and click events that return numbers rather than the
category labels). The plugin also overrides the tick generator to spit out the
categories as ticks instead of the values.
If you need to map a value back to its label, the mapping is always accessible
as "categories" on the axis object, e.g. plot.getAxes().xaxis.categories.
*/
(function ($) {
var options = {
xaxis: {
categories: null
},
yaxis: {
categories: null
}
};
function processRawData(plot, series, data, datapoints) {
// if categories are enabled, we need to disable
// auto-transformation to numbers so the strings are intact
// for later processing
var xCategories = series.xaxis.options.mode === "categories",
yCategories = series.yaxis.options.mode === "categories";
if (!(xCategories || yCategories)) {
return;
}
var format = datapoints.format;
if (!format) {
// FIXME: auto-detection should really not be defined here
var s = series;
format = [];
format.push({ x: true, number: true, required: true, computeRange: true});
format.push({ y: true, number: true, required: true, computeRange: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
var autoScale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
format.push({ y: true, number: true, required: false, defaultValue: 0, computeRange: autoScale });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
datapoints.format = format;
}
for (var m = 0; m < format.length; ++m) {
if (format[m].x && xCategories) {
format[m].number = false;
}
if (format[m].y && yCategories) {
format[m].number = false;
format[m].computeRange = false;
}
}
}
function getNextIndex(categories) {
var index = -1;
for (var v in categories) {
if (categories[v] > index) {
index = categories[v];
}
}
return index + 1;
}
function categoriesTickGenerator(axis) {
var res = [];
for (var label in axis.categories) {
var v = axis.categories[label];
if (v >= axis.min && v <= axis.max) {
res.push([v, label]);
}
}
res.sort(function (a, b) { return a[0] - b[0]; });
return res;
}
function setupCategoriesForAxis(series, axis, datapoints) {
if (series[axis].options.mode !== "categories") {
return;
}
if (!series[axis].categories) {
// parse options
var c = {}, o = series[axis].options.categories || {};
if ($.isArray(o)) {
for (var i = 0; i < o.length; ++i) {
c[o[i]] = i;
}
} else {
for (var v in o) {
c[v] = o[v];
}
}
series[axis].categories = c;
}
// fix ticks
if (!series[axis].options.ticks) {
series[axis].options.ticks = categoriesTickGenerator;
}
transformPointsOnAxis(datapoints, axis, series[axis].categories);
}
function transformPointsOnAxis(datapoints, axis, categories) {
// go through the points, transforming them
var points = datapoints.points,
ps = datapoints.pointsize,
format = datapoints.format,
formatColumn = axis.charAt(0),
index = getNextIndex(categories);
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null) {
continue;
}
for (var m = 0; m < ps; ++m) {
var val = points[i + m];
if (val == null || !format[m][formatColumn]) {
continue;
}
if (!(val in categories)) {
categories[val] = index;
++index;
}
points[i + m] = categories[val];
}
}
}
function processDatapoints(plot, series, datapoints) {
setupCategoriesForAxis(series, "xaxis", datapoints);
setupCategoriesForAxis(series, "yaxis", datapoints);
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.processDatapoints.push(processDatapoints);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'categories',
version: '1.0'
});
})(jQuery);
/** ## jquery.flot.composeImages.js
This plugin is used to expose a function used to overlap several canvases and
SVGs, for the purpose of creating a snaphot out of them.
### When composeImages is used:
When multiple canvases and SVGs have to be overlapped into a single image
and their offset on the page, must be preserved.
### Where can be used:
In creating a downloadable snapshot of the plots, axes, cursors etc of a graph.
### How it works:
The entry point is composeImages function. It expects an array of objects,
which should be either canvases or SVGs (or a mix). It does a prevalidation
of them, by verifying if they will be usable or not, later in the flow.
After selecting only usable sources, it passes them to getGenerateTempImg
function, which generates temporary images out of them. This function
expects that some of the passed sources (canvas or SVG) may still have
problems being converted to an image and makes sure the promises system,
used by composeImages function, moves forward. As an example, SVGs with
missing information from header or with unsupported content, may lead to
failure in generating the temporary image. Temporary images are required
mostly on extracting content from SVGs, but this is also where the x/y
offsets are extracted for each image which will be added. For SVGs in
particular, their CSS rules have to be applied.
After all temporary images are generated, they are overlapped using
getExecuteImgComposition function. This is where the destination canvas
is set to the proper dimensions. It is then output by composeImages.
This function returns a promise, which can be used to wait for the whole
composition process. It requires to be asynchronous, because this is how
temporary images load their data.
*/
(function($) {
"use strict";
const GENERALFAILURECALLBACKERROR = -100; //simply a negative number
const SUCCESSFULIMAGEPREPARATION = 0;
const EMPTYARRAYOFIMAGESOURCES = -1;
const NEGATIVEIMAGESIZE = -2;
var pixelRatio = 1;
var browser = $.plot.browser;
var getPixelRatio = browser.getPixelRatio;
function composeImages(canvasOrSvgSources, destinationCanvas) {
var validCanvasOrSvgSources = canvasOrSvgSources.filter(isValidSource);
pixelRatio = getPixelRatio(destinationCanvas.getContext('2d'));
var allImgCompositionPromises = validCanvasOrSvgSources.map(function(validCanvasOrSvgSource) {
var tempImg = new Image();
var currentPromise = new Promise(getGenerateTempImg(tempImg, validCanvasOrSvgSource));
return currentPromise;
});
var lastPromise = Promise.all(allImgCompositionPromises).then(getExecuteImgComposition(destinationCanvas), failureCallback);
return lastPromise;
}
function isValidSource(canvasOrSvgSource) {
var isValidFromCanvas = true;
var isValidFromContent = true;
if ((canvasOrSvgSource === null) || (canvasOrSvgSource === undefined)) {
isValidFromContent = false;
} else {
if (canvasOrSvgSource.tagName === 'CANVAS') {
if ((canvasOrSvgSource.getBoundingClientRect().right === canvasOrSvgSource.getBoundingClientRect().left) ||
(canvasOrSvgSource.getBoundingClientRect().bottom === canvasOrSvgSource.getBoundingClientRect().top)) {
isValidFromCanvas = false;
}
}
}
return isValidFromContent && isValidFromCanvas && (window.getComputedStyle(canvasOrSvgSource).visibility === 'visible');
}
function getGenerateTempImg(tempImg, canvasOrSvgSource) {
tempImg.sourceDescription = '<info className="' + canvasOrSvgSource.className + '" tagName="' + canvasOrSvgSource.tagName + '" id="' + canvasOrSvgSource.id + '">';
tempImg.sourceComponent = canvasOrSvgSource;
return function doGenerateTempImg(successCallbackFunc, failureCallbackFunc) {
tempImg.onload = function(evt) {
tempImg.successfullyLoaded = true;
successCallbackFunc(tempImg);
};
tempImg.onabort = function(evt) {
tempImg.successfullyLoaded = false;
console.log('Can\'t generate temp image from ' + tempImg.sourceDescription + '. It is possible that it is missing some properties or its content is not supported by this browser. Source component:', tempImg.sourceComponent);
successCallbackFunc(tempImg); //call successCallback, to allow snapshot of all working images
};
tempImg.onerror = function(evt) {
tempImg.successfullyLoaded = false;
console.log('Can\'t generate temp image from ' + tempImg.sourceDescription + '. It is possible that it is missing some properties or its content is not supported by this browser. Source component:', tempImg.sourceComponent);
successCallbackFunc(tempImg); //call successCallback, to allow snapshot of all working images
};
generateTempImageFromCanvasOrSvg(canvasOrSvgSource, tempImg);
};
}
function getExecuteImgComposition(destinationCanvas) {
return function executeImgComposition(tempImgs) {
var compositionResult = copyImgsToCanvas(tempImgs, destinationCanvas);
return compositionResult;
};
}
function copyCanvasToImg(canvas, img) {
img.src = canvas.toDataURL('image/png');
}
function getCSSRules(document) {
var styleSheets = document.styleSheets,
rulesList = [];
for (var i = 0; i < styleSheets.length; i++) {
// in Chrome, the external CSS files are empty when the page is directly loaded from disk
var rules = styleSheets[i].cssRules || [];
for (var j = 0; j < rules.length; j++) {
var rule = rules[j];
rulesList.push(rule.cssText);
}
}
return rulesList;
}
function embedCSSRulesInSVG(rules, svg) {
var text = [
'<svg class="snapshot ' + svg.classList + '" width="' + svg.width.baseVal.value * pixelRatio + '" height="' + svg.height.baseVal.value * pixelRatio + '" viewBox="0 0 ' + svg.width.baseVal.value + ' ' + svg.height.baseVal.value + '" xmlns="http://www.w3.org/2000/svg">',
'<style>',
'/* <![CDATA[ */',
rules.join('\n'),
'/* ]]> */',
'</style>',
svg.innerHTML,
'</svg>'
].join('\n');
return text;
}
function copySVGToImgMostBrowsers(svg, img) {
var rules = getCSSRules(document),
source = embedCSSRulesInSVG(rules, svg);
source = patchSVGSource(source);
var blob = new Blob([source], {type: "image/svg+xml;charset=utf-8"}),
domURL = self.URL || self.webkitURL || self,
url = domURL.createObjectURL(blob);
img.src = url;
}
function copySVGToImgSafari(svg, img) {
// Use this method to convert a string buffer array to a binary string.
// Do so by breaking up large strings into smaller substrings; this is necessary to avoid the
// "maximum call stack size exceeded" exception that can happen when calling 'String.fromCharCode.apply'
// with a very long array.
function buildBinaryString (arrayBuffer) {
var binaryString = "";
const utf8Array = new Uint8Array(arrayBuffer);
const blockSize = 16384;
for (var i = 0; i < utf8Array.length; i = i + blockSize) {
const binarySubString = String.fromCharCode.apply(null, utf8Array.subarray(i, i + blockSize));
binaryString = binaryString + binarySubString;
}
return binaryString;
};
var rules = getCSSRules(document),
source = embedCSSRulesInSVG(rules, svg),
data,
utf8BinaryString;
source = patchSVGSource(source);
// Encode the string as UTF-8 and convert it to a binary string. The UTF-8 encoding is required to
// capture unicode characters correctly.
utf8BinaryString = buildBinaryString(new (TextEncoder || TextEncoderLite)('utf-8').encode(source));
data = "data:image/svg+xml;base64," + btoa(utf8BinaryString);
img.src = data;
}
function patchSVGSource(svgSource) {
var source = '';
//add name spaces.
if (!svgSource.match(/^<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/)) {
source = svgSource.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if (!svgSource.match(/^<svg[^>]+"http:\/\/www\.w3\.org\/1999\/xlink"/)) {
source = svgSource.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
//add xml declaration
return '<?xml version="1.0" standalone="no"?>\r\n' + source;
}
function copySVGToImg(svg, img) {
if (browser.isSafari() || browser.isMobileSafari()) {
copySVGToImgSafari(svg, img);
} else {
copySVGToImgMostBrowsers(svg, img);
}
}
function adaptDestSizeToZoom(destinationCanvas, sources) {
function containsSVGs(source) {
return source.srcImgTagName === 'svg';
}
if (sources.find(containsSVGs) !== undefined) {
if (pixelRatio < 1) {
destinationCanvas.width = destinationCanvas.width * pixelRatio;
destinationCanvas.height = destinationCanvas.height * pixelRatio;
}
}
}
function prepareImagesToBeComposed(sources, destination) {
var result = SUCCESSFULIMAGEPREPARATION;
if (sources.length === 0) {
result = EMPTYARRAYOFIMAGESOURCES; //nothing to do if called without sources
} else {
var minX = sources[0].genLeft;
var minY = sources[0].genTop;
var maxX = sources[0].genRight;
var maxY = sources[0].genBottom;
var i = 0;
for (i = 1; i < sources.length; i++) {
if (minX > sources[i].genLeft) {
minX = sources[i].genLeft;
}
if (minY > sources[i].genTop) {
minY = sources[i].genTop;
}
}
for (i = 1; i < sources.length; i++) {
if (maxX < sources[i].genRight) {
maxX = sources[i].genRight;
}
if (maxY < sources[i].genBottom) {
maxY = sources[i].genBottom;
}
}
if ((maxX - minX <= 0) || (maxY - minY <= 0)) {
result = NEGATIVEIMAGESIZE; //this might occur on hidden images
} else {
destination.width = Math.round(maxX - minX);
destination.height = Math.round(maxY - minY);
for (i = 0; i < sources.length; i++) {
sources[i].xCompOffset = sources[i].genLeft - minX;
sources[i].yCompOffset = sources[i].genTop - minY;
}
adaptDestSizeToZoom(destination, sources);
}
}
return result;
}
function copyImgsToCanvas(sources, destination) {
var prepareImagesResult = prepareImagesToBeComposed(sources, destination);
if (prepareImagesResult === SUCCESSFULIMAGEPREPARATION) {
var destinationCtx = destination.getContext('2d');
for (var i = 0; i < sources.length; i++) {
if (sources[i].successfullyLoaded === true) {
destinationCtx.drawImage(sources[i], sources[i].xCompOffset * pixelRatio, sources[i].yCompOffset * pixelRatio);
}
}
}
return prepareImagesResult;
}
function adnotateDestImgWithBoundingClientRect(srcCanvasOrSvg, destImg) {
destImg.genLeft = srcCanvasOrSvg.getBoundingClientRect().left;
destImg.genTop = srcCanvasOrSvg.getBoundingClientRect().top;
if (srcCanvasOrSvg.tagName === 'CANVAS') {
destImg.genRight = destImg.genLeft + srcCanvasOrSvg.width;
destImg.genBottom = destImg.genTop + srcCanvasOrSvg.height;
}
if (srcCanvasOrSvg.tagName === 'svg') {
destImg.genRight = srcCanvasOrSvg.getBoundingClientRect().right;
destImg.genBottom = srcCanvasOrSvg.getBoundingClientRect().bottom;
}
}
function generateTempImageFromCanvasOrSvg(srcCanvasOrSvg, destImg) {
if (srcCanvasOrSvg.tagName === 'CANVAS') {
copyCanvasToImg(srcCanvasOrSvg, destImg);
}
if (srcCanvasOrSvg.tagName === 'svg') {
copySVGToImg(srcCanvasOrSvg, destImg);
}
destImg.srcImgTagName = srcCanvasOrSvg.tagName;
adnotateDestImgWithBoundingClientRect(srcCanvasOrSvg, destImg);
}
function failureCallback() {
return GENERALFAILURECALLBACKERROR;
}
// used for testing
$.plot.composeImages = composeImages;
function init(plot) {
// used to extend the public API of the plot
plot.composeImages = composeImages;
}
$.plot.plugins.push({
init: init,
name: 'composeImages',
version: '1.0'
});
})(jQuery);
/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
crosshair: {
mode: null or "x" or "y" or "xy"
color: color
lineWidth: number
}
Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
crosshair that lets you trace the values on the x axis, "y" enables a
horizontal crosshair and "xy" enables them both. "color" is the color of the
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
the drawn lines (default is 1).
The plugin also adds four public methods:
- setCrosshair( pos )
Set the position of the crosshair. Note that this is cleared if the user
moves the mouse. "pos" is in coordinates of the plot and should be on the
form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
axes), which is coincidentally the same format as what you get from a
"plothover" event. If "pos" is null, the crosshair is cleared.
- clearCrosshair()
Clear the crosshair.
- lockCrosshair(pos)
Cause the crosshair to lock to the current location, no longer updating if
the user moves the mouse. Optionally supply a position (passed on to
setCrosshair()) to move it to.
Example usage:
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
$("#graph").bind( "plothover", function ( evt, position, item ) {
if ( item ) {
// Lock the crosshair to the data point being hovered
myFlot.lockCrosshair({
x: item.datapoint[ 0 ],
y: item.datapoint[ 1 ]
});
} else {
// Return normal crosshair operation
myFlot.unlockCrosshair();
}
});
- unlockCrosshair()
Free the crosshair to move again after locking it.
*/
(function ($) {
var options = {
crosshair: {
mode: null, // one of null, "x", "y" or "xy",
color: "rgba(170, 0, 0, 0.80)",
lineWidth: 1
}
};
function init(plot) {
// position of crosshair in pixels
var crosshair = {x: -1, y: -1, locked: false, highlighted: false};
plot.setCrosshair = function setCrosshair(pos) {
if (!pos) {
crosshair.x = -1;
} else {
var o = plot.p2c(pos);
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
}
plot.triggerRedrawOverlay();
};
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
plot.lockCrosshair = function lockCrosshair(pos) {
if (pos) {
plot.setCrosshair(pos);
}
crosshair.locked = true;
};
plot.unlockCrosshair = function unlockCrosshair() {
crosshair.locked = false;
crosshair.rect = null;
};
function onMouseOut(e) {
if (crosshair.locked) {
return;
}
if (crosshair.x !== -1) {
crosshair.x = -1;
plot.triggerRedrawOverlay();
}
}
function onMouseMove(e) {
var offset = plot.offset();
if (crosshair.locked) {
var mouseX = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
var mouseY = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
if ((mouseX > crosshair.x - 4) && (mouseX < crosshair.x + 4) && (mouseY > crosshair.y - 4) && (mouseY < crosshair.y + 4)) {
if (!crosshair.highlighted) {
crosshair.highlighted = true;
plot.triggerRedrawOverlay();
}
} else {
if (crosshair.highlighted) {
crosshair.highlighted = false;
plot.triggerRedrawOverlay();
}
}
return;
}
if (plot.getSelection && plot.getSelection()) {
crosshair.x = -1; // hide the crosshair while selecting
return;
}
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
plot.triggerRedrawOverlay();
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
if (!plot.getOptions().crosshair.mode) {
return;
}
eventHolder.mouseout(onMouseOut);
eventHolder.mousemove(onMouseMove);
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
var c = plot.getOptions().crosshair;
if (!c.mode) {
return;
}
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
if (crosshair.x !== -1) {
var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
ctx.strokeStyle = c.color;
ctx.lineWidth = c.lineWidth;
ctx.lineJoin = "round";
ctx.beginPath();
if (c.mode.indexOf("x") !== -1) {
var drawX = Math.floor(crosshair.x) + adj;
ctx.moveTo(drawX, 0);
ctx.lineTo(drawX, plot.height());
}
if (c.mode.indexOf("y") !== -1) {
var drawY = Math.floor(crosshair.y) + adj;
ctx.moveTo(0, drawY);
ctx.lineTo(plot.width(), drawY);
}
if (crosshair.locked) {
if (crosshair.highlighted) ctx.fillStyle = 'orange';
else ctx.fillStyle = c.color;
ctx.fillRect(Math.floor(crosshair.x) + adj - 4, Math.floor(crosshair.y) + adj - 4, 8, 8);
}
ctx.stroke();
}
ctx.restore();
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mouseout", onMouseOut);
eventHolder.unbind("mousemove", onMouseMove);
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'crosshair',
version: '1.0'
});
})(jQuery);
/* Flot plugin for plotting error bars.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
Error bars are used to show standard deviation and other statistical
properties in a plot.
* Created by Rui Pereira - rui (dot) pereira (at) gmail (dot) com
This plugin allows you to plot error-bars over points. Set "errorbars" inside
the points series to the axis name over which there will be error values in
your data array (*even* if you do not intend to plot them later, by setting
"show: null" on xerr/yerr).
The plugin supports these options:
series: {
points: {
errorbars: "x" or "y" or "xy",
xerr: {
show: null/false or true,
asymmetric: null/false or true,
upperCap: null or "-" or function,
lowerCap: null or "-" or function,
color: null or color,
radius: null or number
},
yerr: { same options as xerr }
}
}
Each data point array is expected to be of the type:
"x" [ x, y, xerr ]
"y" [ x, y, yerr ]
"xy" [ x, y, xerr, yerr ]
Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and
equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric
error-bars on X and asymmetric on Y would be:
[ x, y, xerr, yerr_lower, yerr_upper ]
By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will
draw a small cap perpendicular to the error bar. They can also be set to a
user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg.
function drawSemiCircle( ctx, x, y, radius ) {
ctx.beginPath();
ctx.arc( x, y, radius, 0, Math.PI, false );
ctx.moveTo( x - radius, y );
ctx.lineTo( x + radius, y );
ctx.stroke();
}
Color and radius both default to the same ones of the points series if not
set. The independent radius parameter on xerr/yerr is useful for the case when
we may want to add error-bars to a line, without showing the interconnecting
points (with radius: 0), and still showing end caps on the error-bars.
shadowSize and lineWidth are derived as well from the points series.
*/
(function ($) {
var options = {
series: {
points: {
errorbars: null, //should be 'x', 'y' or 'xy'
xerr: {err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null},
yerr: {err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}
}
}
};
function processRawData(plot, series, data, datapoints) {
if (!series.points.errorbars) {
return;
}
// x,y values
var format = [
{ x: true, number: true, required: true },
{ y: true, number: true, required: true }
];
var errors = series.points.errorbars;
// error bars - first X then Y
if (errors === 'x' || errors === 'xy') {
// lower / upper error
if (series.points.xerr.asymmetric) {
format.push({ x: true, number: true, required: true });
format.push({ x: true, number: true, required: true });
} else {
format.push({ x: true, number: true, required: true });
}
}
if (errors === 'y' || errors === 'xy') {
// lower / upper error
if (series.points.yerr.asymmetric) {
format.push({ y: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
} else {
format.push({ y: true, number: true, required: true });
}
}
datapoints.format = format;
}
function parseErrors(series, i) {
var points = series.datapoints.points;
// read errors from points array
var exl = null,
exu = null,
eyl = null,
eyu = null;
var xerr = series.points.xerr,
yerr = series.points.yerr;
var eb = series.points.errorbars;
// error bars - first X
if (eb === 'x' || eb === 'xy') {
if (xerr.asymmetric) {
exl = points[i + 2];
exu = points[i + 3];
if (eb === 'xy') {
if (yerr.asymmetric) {
eyl = points[i + 4];
eyu = points[i + 5];
} else {
eyl = points[i + 4];
}
}
} else {
exl = points[i + 2];
if (eb === 'xy') {
if (yerr.asymmetric) {
eyl = points[i + 3];
eyu = points[i + 4];
} else {
eyl = points[i + 3];
}
}
}
// only Y
} else {
if (eb === 'y') {
if (yerr.asymmetric) {
eyl = points[i + 2];
eyu = points[i + 3];
} else {
eyl = points[i + 2];
}
}
}
// symmetric errors?
if (exu == null) exu = exl;
if (eyu == null) eyu = eyl;
var errRanges = [exl, exu, eyl, eyu];
// nullify if not showing
if (!xerr.show) {
errRanges[0] = null;
errRanges[1] = null;
}
if (!yerr.show) {
errRanges[2] = null;
errRanges[3] = null;
}
return errRanges;
}
function drawSeriesErrors(plot, ctx, s) {
var points = s.datapoints.points,
ps = s.datapoints.pointsize,
ax = [s.xaxis, s.yaxis],
radius = s.points.radius,
err = [s.points.xerr, s.points.yerr],
tmp;
//sanity check, in case some inverted axis hack is applied to flot
var invertX = false;
if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) {
invertX = true;
tmp = err[0].lowerCap;
err[0].lowerCap = err[0].upperCap;
err[0].upperCap = tmp;
}
var invertY = false;
if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) {
invertY = true;
tmp = err[1].lowerCap;
err[1].lowerCap = err[1].upperCap;
err[1].upperCap = tmp;
}
for (var i = 0; i < s.datapoints.points.length; i += ps) {
//parse
var errRanges = parseErrors(s, i);
//cycle xerr & yerr
for (var e = 0; e < err.length; e++) {
var minmax = [ax[e].min, ax[e].max];
//draw this error?
if (errRanges[e * err.length]) {
//data coordinates
var x = points[i],
y = points[i + 1];
//errorbar ranges
var upper = [x, y][e] + errRanges[e * err.length + 1],
lower = [x, y][e] - errRanges[e * err.length];
//points outside of the canvas
if (err[e].err === 'x') {
if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max) {
continue;
}
}
if (err[e].err === 'y') {
if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max) {
continue;
}
}
// prevent errorbars getting out of the canvas
var drawUpper = true,
drawLower = true;
if (upper > minmax[1]) {
drawUpper = false;
upper = minmax[1];
}
if (lower < minmax[0]) {
drawLower = false;
lower = minmax[0];
}
//sanity check, in case some inverted axis hack is applied to flot
if ((err[e].err === 'x' && invertX) || (err[e].err === 'y' && invertY)) {
//swap coordinates
tmp = lower;
lower = upper;
upper = tmp;
tmp = drawLower;
drawLower = drawUpper;
drawUpper = tmp;
tmp = minmax[0];
minmax[0] = minmax[1];
minmax[1] = tmp;
}
// convert to pixels
x = ax[0].p2c(x);
y = ax[1].p2c(y);
upper = ax[e].p2c(upper);
lower = ax[e].p2c(lower);
minmax[0] = ax[e].p2c(minmax[0]);
minmax[1] = ax[e].p2c(minmax[1]);
//same style as points by default
var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth,
sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize;
//shadow as for points
if (lw > 0 && sw > 0) {
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w / 2, minmax);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w / 2, minmax);
}
ctx.strokeStyle = err[e].color
? err[e].color
: s.color;
ctx.lineWidth = lw;
//draw it
drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax);
}
}
}
}
function drawError(ctx, err, x, y, upper, lower, drawUpper, drawLower, radius, offset, minmax) {
//shadow offset
y += offset;
upper += offset;
lower += offset;
// error bar - avoid plotting over circles
if (err.err === 'x') {
if (upper > x + radius) drawPath(ctx, [[upper, y], [Math.max(x + radius, minmax[0]), y]]);
else drawUpper = false;
if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius, minmax[1]), y], [lower, y]]);
else drawLower = false;
} else {
if (upper < y - radius) drawPath(ctx, [[x, upper], [x, Math.min(y - radius, minmax[0])]]);
else drawUpper = false;
if (lower > y + radius) drawPath(ctx, [[x, Math.max(y + radius, minmax[1])], [x, lower]]);
else drawLower = false;
}
//internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps
//this is a way to get errorbars on lines without visible connecting dots
radius = err.radius != null
? err.radius
: radius;
// upper cap
if (drawUpper) {
if (err.upperCap === '-') {
if (err.err === 'x') drawPath(ctx, [[upper, y - radius], [upper, y + radius]]);
else drawPath(ctx, [[x - radius, upper], [x + radius, upper]]);
} else if ($.isFunction(err.upperCap)) {
if (err.err === 'x') err.upperCap(ctx, upper, y, radius);
else err.upperCap(ctx, x, upper, radius);
}
}
// lower cap
if (drawLower) {
if (err.lowerCap === '-') {
if (err.err === 'x') drawPath(ctx, [[lower, y - radius], [lower, y + radius]]);
else drawPath(ctx, [[x - radius, lower], [x + radius, lower]]);
} else if ($.isFunction(err.lowerCap)) {
if (err.err === 'x') err.lowerCap(ctx, lower, y, radius);
else err.lowerCap(ctx, x, lower, radius);
}
}
}
function drawPath(ctx, pts) {
ctx.beginPath();
ctx.moveTo(pts[0][0], pts[0][1]);
for (var p = 1; p < pts.length; p++) {
ctx.lineTo(pts[p][0], pts[p][1]);
}
ctx.stroke();
}
function draw(plot, ctx) {
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
$.each(plot.getData(), function (i, s) {
if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show)) {
drawSeriesErrors(plot, ctx, s);
}
});
ctx.restore();
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.draw.push(draw);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'errorbars',
version: '1.0'
});
})(jQuery);
/* Flot plugin for computing bottoms for filled line and bar charts.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
The case: you've got two series that you want to fill the area between. In Flot
terms, you need to use one as the fill bottom of the other. You can specify the
bottom of each data point as the third coordinate manually, or you can use this
plugin to compute it for you.
In order to name the other series, you need to give it an id, like this:
var dataset = [
{ data: [ ... ], id: "foo" } , // use default bottom
{ data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom
];
$.plot($("#placeholder"), dataset, { lines: { show: true, fill: true }});
As a convenience, if the id given is a number that doesn't appear as an id in
the series, it is interpreted as the index in the array instead (so fillBetween:
0 can also mean the first series).
Internally, the plugin modifies the datapoints in each series. For line series,
extra data points might be inserted through interpolation. Note that at points
where the bottom line is not defined (due to a null point or start/end of line),
the current line will show a gap too. The algorithm comes from the
jquery.flot.stack.js plugin, possibly some code could be shared.
*/
(function ($) {
var options = {
series: {
fillBetween: null // or number
}
};
function init(plot) {
function findBottomSeries(s, allseries) {
var i;
for (i = 0; i < allseries.length; ++i) {
if (allseries[ i ].id === s.fillBetween) {
return allseries[ i ];
}
}
if (typeof s.fillBetween === "number") {
if (s.fillBetween < 0 || s.fillBetween >= allseries.length) {
return null;
}
return allseries[ s.fillBetween ];
}
return null;
}
function computeFormat(plot, s, data, datapoints) {
if (s.fillBetween == null) {
return;
}
format = datapoints.format;
var plotHasId = function(id) {
var plotData = plot.getData();
for (i = 0; i < plotData.length; i++) {
if (plotData[i].id === id) {
return true;
}
}
return false;
}
if (!format) {
format = [];
format.push({
x: true,
number: true,
computeRange: s.xaxis.options.autoScale !== 'none',
required: true
});
format.push({
y: true,
number: true,
computeRange: s.yaxis.options.autoScale !== 'none',
required: true
});
if (s.fillBetween !== undefined && s.fillBetween !== '' && plotHasId(s.fillBetween) && s.fillBetween !== s.id) {
format.push({
x: false,
y: true,
number: true,
required: false,
computeRange: s.yaxis.options.autoScale !== 'none',
defaultValue: 0
});
}
datapoints.format = format;
}
}
function computeFillBottoms(plot, s, datapoints) {
if (s.fillBetween == null) {
return;
}
var other = findBottomSeries(s, plot.getData());
if (!other) {
return;
}
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
withbottom = ps > 2 && datapoints.format[2].y,
withsteps = withlines && s.lines.steps,
fromgap = true,
i = 0,
j = 0,
l, m;
while (true) {
if (i >= points.length) {
break;
}
l = newpoints.length;
if (points[ i ] == null) {
// copy gaps
for (m = 0; m < ps; ++m) {
newpoints.push(points[ i + m ]);
}
i += ps;
} else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m) {
newpoints.push(points[ i + m ]);
}
}
i += ps;
} else if (otherpoints[ j ] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m) {
newpoints.push(null);
}
fromgap = true;
j += otherps;
} else {
// cases where we actually got two points
px = points[ i ];
py = points[ i + 1 ];
qx = otherpoints[ j ];
qy = otherpoints[ j + 1 ];
bottom = 0;
if (px === qx) {
for (m = 0; m < ps; ++m) {
newpoints.push(points[ i + m ]);
}
//newpoints[ l + 1 ] += qy;
bottom = qy;
i += ps;
j += otherps;
} else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[ i - ps ] != null) {
intery = py + (points[ i - ps + 1 ] - py) * (qx - px) / (points[ i - ps ] - px);
newpoints.push(qx);
newpoints.push(intery);
for (m = 2; m < ps; ++m) {
newpoints.push(points[ i + m ]);
}
bottom = qy;
}
j += otherps;
} else {
// px < qx
// if we come from a gap, we just skip this point
if (fromgap && withlines) {
i += ps;
continue;
}
for (m = 0; m < ps; ++m) {
newpoints.push(points[ i + m ]);
}
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[ j - otherps ] != null) {
bottom = qy + (otherpoints[ j - otherps + 1 ] - qy) * (px - qx) / (otherpoints[ j - otherps ] - qx);
}
//newpoints[l + 1] += bottom;
i += ps;
}
fromgap = false;
if (l !== newpoints.length && withbottom) {
newpoints[ l + 2 ] = bottom;
}
}
// maintain the line steps invariant
if (withsteps && l !== newpoints.length && l > 0 &&
newpoints[ l ] !== null &&
newpoints[ l ] !== newpoints[ l - ps ] &&
newpoints[ l + 1 ] !== newpoints[ l - ps + 1 ]) {
for (m = 0; m < ps; ++m) {
newpoints[ l + ps + m ] = newpoints[ l + m ];
}
newpoints[ l + 1 ] = newpoints[ l - ps + 1 ];
}
}
datapoints.points = newpoints;
}
plot.hooks.processRawData.push(computeFormat);
plot.hooks.processDatapoints.push(computeFillBottoms);
}
$.plot.plugins.push({
init: init,
options: options,
name: "fillbetween",
version: "1.0"
});
})(jQuery);
/* Support for flat 1D data series.
A 1D flat data series is a data series in the form of a regular 1D array. The
main reason for using a flat data series is that it performs better, consumes
less memory and generates less garbage collection than the regular flot format.
Example:
plot.setData([[[0,0], [1,1], [2,2], [3,3]]]); // regular flot format
plot.setData([{flatdata: true, data: [0, 1, 2, 3]}]); // flatdata format
Set series.flatdata to true to enable this plugin.
You can use series.start to specify the starting index of the series (default is 0)
You can use series.step to specify the interval between consecutive indexes of the series (default is 1)
*/
/* global jQuery*/
(function ($) {
'use strict';
function process1DRawData(plot, series, data, datapoints) {
if (series.flatdata === true) {
var start = series.start || 0;
var step = typeof series.step === 'number' ? series.step : 1;
datapoints.pointsize = 2;
for (var i = 0, j = 0; i < data.length; i++, j += 2) {
datapoints.points[j] = start + (i * step);
datapoints.points[j + 1] = data[i];
}
if (datapoints.points !== undefined) {
datapoints.points.length = data.length * 2;
} else {
datapoints.points = [];
}
}
}
$.plot.plugins.push({
init: function(plot) {
plot.hooks.processRawData.push(process1DRawData);
},
name: 'flatdata',
version: '0.0.2'
});
})(jQuery);
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment