pax_global_header00006660000000000000000000000064122425605430014515gustar00rootroot0000000000000052 comment=6d85ab7daf5456849277649dbdfb764d0f7017a5 erlang-bear-0.8.0+dfsg/000077500000000000000000000000001224256054300146205ustar00rootroot00000000000000erlang-bear-0.8.0+dfsg/LICENSE000066400000000000000000000251421224256054300156310ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. erlang-bear-0.8.0+dfsg/README.md000066400000000000000000000004141224256054300160760ustar00rootroot00000000000000### bear : a set of statistics functions for erlang Currently bear is focused on use inside the Folsom Erlang metrics library but all of these functions are generic and useful in other situations. Pull requests accepted! #### Available under the Apache 2.0 License erlang-bear-0.8.0+dfsg/rebar.config000066400000000000000000000000751224256054300171040ustar00rootroot00000000000000{deps, []}. {erl_opts, [debug_info]}. {cover_enabled, true}. erlang-bear-0.8.0+dfsg/src/000077500000000000000000000000001224256054300154075ustar00rootroot00000000000000erlang-bear-0.8.0+dfsg/src/bear.app.src000066400000000000000000000001651224256054300176120ustar00rootroot00000000000000{application, bear, [ {description, ""}, {vsn, git}, {registered, []}, {applications, []}, {env, []} ]}. erlang-bear-0.8.0+dfsg/src/bear.erl000066400000000000000000000407161224256054300170340ustar00rootroot00000000000000%%% %%% Copyright 2011, Boundary %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- %%% File: bear.erl %%% @author joe williams %%% @doc %%% statistics functions for calucating based on id and a list of values %%% @end %%%------------------------------------------------------------------ -module(bear). -compile([export_all]). -export([ get_statistics/1, get_statistics/2 ]). -define(HIST_BINS, 10). -define(STATS_MIN, 5). -record(scan_result, {n=0, sumX=0, sumXX=0, sumInv=0, sumLog, max, min}). -record(scan_result2, {x2=0, x3=0, x4=0}). -compile([native]). get_statistics([_,_,_,_,_|_] = Values) -> Scan_res = scan_values(Values), Scan_res2 = scan_values2(Values, Scan_res), Variance = variance(Scan_res, Scan_res2), SortedValues = lists:sort(Values), [ {min, Scan_res#scan_result.min}, {max, Scan_res#scan_result.max}, {arithmetic_mean, arithmetic_mean(Scan_res)}, {geometric_mean, geometric_mean(Scan_res)}, {harmonic_mean, harmonic_mean(Scan_res)}, {median, percentile(SortedValues, Scan_res, 0.5)}, {variance, Variance}, {standard_deviation, std_deviation(Scan_res, Scan_res2)}, {skewness, skewness(Scan_res, Scan_res2)}, {kurtosis, kurtosis(Scan_res, Scan_res2)}, {percentile, [ {50, percentile(SortedValues, Scan_res, 0.50)}, {75, percentile(SortedValues, Scan_res, 0.75)}, {90, percentile(SortedValues, Scan_res, 0.90)}, {95, percentile(SortedValues, Scan_res, 0.95)}, {99, percentile(SortedValues, Scan_res, 0.99)}, {999, percentile(SortedValues, Scan_res, 0.999)} ] }, {histogram, get_histogram(Values, Scan_res, Scan_res2)}, {n, Scan_res#scan_result.n} ]; get_statistics(Values) when is_list(Values) -> [ {min, 0.0}, {max, 0.0}, {arithmetic_mean, 0.0}, {geometric_mean, 0.0}, {harmonic_mean, 0.0}, {median, 0.0}, {variance, 0.0}, {standard_deviation, 0.0}, {skewness, 0.0}, {kurtosis, 0.0}, {percentile, [ {50, 0.0}, {75, 0.0}, {90, 0.0}, {95, 0.0}, {99, 0.0}, {999, 0.0} ] }, {histogram, [{0, 0}]}, {n, 0} ]. get_statistics_subset([_,_,_,_,_|_] = Values, Items) -> Length = length(Values), if Length < ?STATS_MIN -> [I || {K,_} = I <- get_statistics([]), lists:member(K, Items) orelse K==percentiles]; true -> SortedValues = lists:sort(Values), Steps = calc_steps(Items), Scan_res = if Steps > 1 -> scan_values(Values); true -> [] end, Scan_res2 = if Steps > 2 -> scan_values2(Values, Scan_res); true -> [] end, report_subset(Items, Length, SortedValues, Scan_res, Scan_res2) end; get_statistics_subset(Values, Items) when is_list(Values) -> [{Item, 0.0} || Item <- Items]. calc_steps(Items) -> lists:foldl(fun({I,_},Acc) -> erlang:max(level(I), Acc); (I,Acc) -> erlang:max(level(I), Acc) end, 1, Items). level(standard_deviation) -> 3; level(variance ) -> 3; level(skewness ) -> 3; level(kurtosis ) -> 3; level(histogram ) -> 3; level(arithmetic_mean ) -> 2; level(geometric_mean ) -> 2; level(harmonic_mean ) -> 2; level(_) -> 1. report_subset(Items, N, SortedValues, Scan_res, Scan_res2) -> lists:map( fun(min) -> {min, hd(SortedValues)}; (max) -> {max, lists:last(SortedValues)}; (arithmetic_mean) -> {arithmetic_mean, arithmetic_mean(Scan_res)}; (harmonic_mean) -> {harmonic_mean, harmonic_mean(Scan_res)}; (geometric_mean) -> {geometric_mean, geometric_mean(Scan_res)}; (median) -> {median, percentile(SortedValues, #scan_result{n = N}, 0.5)}; (variance) -> {variance, variance(Scan_res, Scan_res2)}; (standard_deviation=I) -> {I, std_deviation(Scan_res, Scan_res2)}; (skewness) -> {skewness, skewness(Scan_res, Scan_res2)}; (kurtosis) -> {kurtosis, kurtosis(Scan_res, Scan_res2)}; ({percentile,Ps}) -> {percentile, percentiles(Ps, N, SortedValues)}; (histogram) -> {histogram, get_histogram(SortedValues, Scan_res, Scan_res2)}; (n) -> {n, N} end, Items). get_statistics(Values, _) when length(Values) < ?STATS_MIN -> 0.0; get_statistics(_, Values) when length(Values) < ?STATS_MIN -> 0.0; get_statistics(Values1, Values2) when length(Values1) /= length(Values2) -> 0.0; get_statistics(Values1, Values2) -> [ {covariance, get_covariance(Values1, Values2)}, {tau, get_kendall_correlation(Values1, Values2)}, {rho, get_pearson_correlation(Values1, Values2)}, {r, get_spearman_correlation(Values1, Values2)} ]. %%%=================================================================== %%% Internal functions %%%=================================================================== scan_values([X|Values]) -> scan_values(Values, #scan_result{n=1, sumX=X, sumXX=X*X, sumLog=math_log(X), max=X, min=X, sumInv=inverse(X)}). scan_values([X|Values], #scan_result{n=N, sumX=SumX, sumXX=SumXX, sumLog=SumLog, max=Max, min=Min, sumInv=SumInv}=Acc) -> scan_values(Values, Acc#scan_result{n=N+1, sumX=SumX+X, sumXX=SumXX+X*X, sumLog=SumLog+math_log(X), max=max(X,Max), min=min(X,Min), sumInv=SumInv+inverse(X)}); scan_values([], Acc) -> Acc. scan_values2(Values, #scan_result{n=N, sumX=SumX}) -> scan_values2(Values, SumX/N, #scan_result2{}). scan_values2([X|Values], Mean, #scan_result2{x2=X2, x3=X3, x4=X4}=Acc) -> Diff = X-Mean, Diff2 = Diff*Diff, Diff3 = Diff2*Diff, Diff4 = Diff2*Diff2, scan_values2(Values, Mean, Acc#scan_result2{x2=X2+Diff2, x3=X3+Diff3, x4=X4+Diff4}); scan_values2([], _, Acc) -> Acc. arithmetic_mean(#scan_result{n=N, sumX=Sum}) -> Sum/N. geometric_mean(#scan_result{n=N, sumLog=SumLog}) -> math:exp(SumLog/N). harmonic_mean(#scan_result{sumInv=0}) -> %% Protect against divide by 0 if we have all 0 values 0; harmonic_mean(#scan_result{n=N, sumInv=Sum}) -> N/Sum. percentile(SortedValues, #scan_result{n=N}, Percentile) when is_list(SortedValues) -> Element = round(Percentile * N), lists:nth(Element, SortedValues). %% Two pass variance %% Results match those given by the 'var' function in R variance(#scan_result{n=N}, #scan_result2{x2=X2}) -> X2/(N-1). std_deviation(Scan_res, Scan_res2) -> math:sqrt(variance(Scan_res, Scan_res2)). %% http://en.wikipedia.org/wiki/Skewness %% %% skewness results should match this R function: %% skewness <- function(x) { %% m3 <- mean((x - mean(x))^3) %% skew <- m3 / (sd(x)^3) %% skew %% } skewness(#scan_result{n=N}=Scan_res, #scan_result2{x3=X3}=Scan_res2) -> case math:pow(std_deviation(Scan_res,Scan_res2), 3) of 0.0 -> 0.0; %% Is this really the correct thing to do here? Else -> (X3/N)/Else end. %% http://en.wikipedia.org/wiki/Kurtosis %% %% results should match this R function: %% kurtosis <- function(x) { %% m4 <- mean((x - mean(x))^4) %% kurt <- m4 / (sd(x)^4) - 3 %% kurt %% } kurtosis(#scan_result{n=N}=Scan_res, #scan_result2{x4=X4}=Scan_res2) -> case math:pow(std_deviation(Scan_res,Scan_res2), 4) of 0.0 -> 0.0; %% Is this really the correct thing to do here? Else -> ((X4/N)/Else) - 3 end. get_histogram(Values, Scan_res, Scan_res2) -> Bins = get_hist_bins(Scan_res#scan_result.min, Scan_res#scan_result.max, std_deviation(Scan_res, Scan_res2), length(Values) ), Dict = lists:foldl(fun (Value, Dict) -> update_bin(Value, Bins, Dict) end, dict:from_list([{Bin, 0} || Bin <- Bins]), Values), lists:sort(dict:to_list(Dict)). update_bin(Value, [Bin|_Bins], Dict) when Value =< Bin -> dict:update_counter(Bin, 1, Dict); update_bin(Values, [_Bin|Bins], Dict) -> update_bin(Values, Bins, Dict). %% two pass covariance %% (http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Covariance) %% matches results given by excel's 'covar' function get_covariance(Values, _) when length(Values) < ?STATS_MIN -> 0.0; get_covariance(_, Values) when length(Values) < ?STATS_MIN -> 0.0; get_covariance(Values1, Values2) when length(Values1) /= length(Values2) -> 0.0; get_covariance(Values1, Values2) -> {SumX, SumY, N} = foldl2(fun (X, Y, {SumX, SumY, N}) -> {SumX+X, SumY+Y, N+1} end, {0,0,0}, Values1, Values2), MeanX = SumX/N, MeanY = SumY/N, Sum = foldl2(fun (X, Y, Sum) -> Sum + ((X - MeanX) * (Y - MeanY)) end, 0, Values1, Values2), Sum/N. get_kendall_correlation(Values, _) when length(Values) < ?STATS_MIN -> 0.0; get_kendall_correlation(_, Values) when length(Values) < ?STATS_MIN -> 0.0; get_kendall_correlation(Values1, Values2) when length(Values1) /= length(Values2) -> 0.0; get_kendall_correlation(Values1, Values2) -> bear:kendall_correlation(Values1, Values2). get_spearman_correlation(Values, _) when length(Values) < ?STATS_MIN -> 0.0; get_spearman_correlation(_, Values) when length(Values) < ?STATS_MIN -> 0.0; get_spearman_correlation(Values1, Values2) when length(Values1) /= length(Values2) -> 0.0; get_spearman_correlation(Values1, Values2) -> TR1 = ranks_of(Values1), TR2 = ranks_of(Values2), Numerator = 6 * foldl2(fun (X, Y, Acc) -> Diff = X-Y, Acc + Diff*Diff end, 0, TR1,TR2), N = length(Values1), Denominator = math:pow(N,3)-N, 1-(Numerator/Denominator). ranks_of(Values) when is_list(Values) -> [Fst|Rest] = revsort(Values), TRs = ranks_of(Rest, [], 2, Fst, 1), Dict = gb_trees:from_orddict(TRs), L = lists:foldl(fun (Val, Acc) -> Rank = gb_trees:get(Val, Dict), [Rank|Acc] end, [], Values), lists:reverse(L). ranks_of([E|Es], Acc, N, P, S) -> ranks_of(Es,[{P,(S+N-1)/2}|Acc], N+1, E, N); ranks_of([], Acc, N, P, S) -> [{P,(S+N-1)/2}|Acc]. get_pearson_correlation(Values, _) when length(Values) < ?STATS_MIN -> 0.0; get_pearson_correlation(_, Values) when length(Values) < ?STATS_MIN -> 0.0; get_pearson_correlation(Values1, Values2) when length(Values1) /= length(Values2) -> 0.0; get_pearson_correlation(Values1, Values2) -> {SumX, SumY, SumXX, SumYY, SumXY, N} = foldl2(fun (X,Y,{SX, SY, SXX, SYY, SXY, N}) -> {SX+X, SY+Y, SXX+X*X, SYY+Y*Y, SXY+X*Y, N+1} end, {0,0,0,0,0,0}, Values1, Values2), Numer = (N*SumXY) - (SumX * SumY), case math:sqrt(((N*SumXX)-(SumX*SumX)) * ((N*SumYY)-(SumY*SumY))) of 0.0 -> 0.0; %% Is this really the correct thing to do here? Denom -> Numer/Denom end. revsort(L) -> lists:reverse(lists:sort(L)). %% Foldl over two lists foldl2(F, Acc, [I1|L1], [I2|L2]) when is_function(F,3) -> foldl2(F, F(I1, I2, Acc), L1, L2); foldl2(_F, Acc, [], []) -> Acc. %% wrapper for math:log/1 to avoid dividing by zero math_log(0) -> 1; math_log(0.0) -> 1.0; math_log(X) when X < 0 -> 0; % it's not possible to take a log of a negative number, return 0 math_log(X) -> math:log(X). %% wrapper for calculating inverse to avoid dividing by zero inverse(0) -> 0; inverse(0.0) -> 0.0; inverse(X) -> 1/X. get_hist_bins(Min, Max, StdDev, Count) -> BinWidth = get_bin_width(StdDev, Count), BinCount = get_bin_count(Min, Max, BinWidth), case get_bin_list(BinWidth, BinCount, []) of List when length(List) =< 1 -> [Max]; Bins -> %% add Min to Bins [Bin + Min || Bin <- Bins] end. get_bin_list(Width, Bins, Acc) when Bins > length(Acc) -> Bin = ((length(Acc) + 1) * Width ), get_bin_list(Width, Bins, [round_bin(Bin)| Acc]); get_bin_list(_, _, Acc) -> lists:usort(Acc). round_bin(Bin) -> Base = case erlang:trunc(math:pow(10, round(math:log10(Bin) - 1))) of 0 -> 1; Else -> Else end, %io:format("bin ~p, base ~p~n", [Bin, Base]), round_bin(Bin, Base). round_bin(Bin, Base) when Bin rem Base == 0 -> Bin; round_bin(Bin, Base) -> Bin + Base - (Bin rem Base). % the following is up for debate as far as what the best method % of choosing bin counts and widths. these seem to work *good enough* % in my testing % bin width based on Sturges % http://www.jstor.org/pss/2965501 get_bin_width(StdDev, Count) -> %io:format("stddev: ~p, count: ~p~n", [StdDev, Count]), case round((3.5 * StdDev) / math:pow(Count, 0.3333333)) of 0 -> 1; Else -> Else end. % based on the simple ceilng function at % http://en.wikipedia.org/wiki/Histograms#Number_of_bins_and_width % with a modification to attempt to get on bin beyond the max value get_bin_count(Min, Max, Width) -> %io:format("min: ~p, max: ~p, width ~p~n", [Min, Max, Width]), round((Max - Min) / Width) + 1. %% taken from http://crunchyd.com/scutil/ %% All code here is MIT Licensed %% http://scutil.com/license.html % seems to match the value returned by the 'cor' (method="kendal") R function % http://en.wikipedia.org/wiki/Kendall_tau_rank_correlation_coefficient kendall_correlation(List1, List2) when is_list(List1), is_list(List2) -> {RA,_} = lists:unzip(tied_ordered_ranking(List1)), {RB,_} = lists:unzip(tied_ordered_ranking(List2)), Ordering = lists:keysort(1, lists:zip(RA,RB)), {_,OrdB} = lists:unzip(Ordering), N = length(List1), P = lists:sum(kendall_right_of(OrdB, [])), -(( (4*P) / (N * (N - 1))) - 1). simple_ranking(List) when is_list(List) -> lists:zip(lists:seq(1,length(List)),lists:reverse(lists:sort(List))). tied_ranking(List) -> tied_rank_worker(simple_ranking(List), [], no_prev_value). tied_ordered_ranking(List) when is_list(List) -> tied_ordered_ranking(List, tied_ranking(List), []). tied_ordered_ranking([], [], Work) -> lists:reverse(Work); tied_ordered_ranking([Front|Rem], Ranks, Work) -> {value,Item} = lists:keysearch(Front,2,Ranks), {IRank,Front} = Item, tied_ordered_ranking(Rem, Ranks--[Item], [{IRank,Front}]++Work). kendall_right_of([], Work) -> lists:reverse(Work); kendall_right_of([F|R], Work) -> kendall_right_of(R, [kendall_right_of_item(F,R)]++Work). kendall_right_of_item(B, Rem) -> length([R || R <- Rem, R < B]). tied_add_prev(Work, {FoundAt, NewValue}) -> lists:duplicate( length(FoundAt), {lists:sum(FoundAt)/length(FoundAt), NewValue} ) ++ Work. tied_rank_worker([], Work, PrevValue) -> lists:reverse(tied_add_prev(Work, PrevValue)); tied_rank_worker([Item|Remainder], Work, PrevValue) -> case PrevValue of no_prev_value -> {BaseRank,BaseVal} = Item, tied_rank_worker(Remainder, Work, {[BaseRank],BaseVal}); {FoundAt,OldVal} -> case Item of {Id,OldVal} -> tied_rank_worker(Remainder, Work, {[Id]++FoundAt,OldVal}); {Id,NewVal} -> tied_rank_worker(Remainder, tied_add_prev(Work, PrevValue), {[Id],NewVal}) end end. percentiles(Ps, N, Values) -> Items = [{P, perc(P, N)} || P <- Ps], pick_items(Values, 1, Items). pick_items([H|_] = L, P, [{Tag,P}|Ps]) -> [{Tag,H} | pick_items(L, P, Ps)]; pick_items([_|T], P, Ps) -> pick_items(T, P+1, Ps); pick_items([], _, Ps) -> [{Tag,undefined} || {Tag,_} <- Ps]. perc(P, Len) when is_integer(P), 0 =< P, P =< 100 -> V = round(P * Len / 100), erlang:max(1, V); perc(P, Len) when is_integer(P), 100 =< P, P =< 1000 -> V = round(P * Len / 1000), erlang:max(1, V); perc(P, Len) when is_float(P), 0 =< P, P =< 1 -> erlang:max(1, round(P * Len)). erlang-bear-0.8.0+dfsg/test/000077500000000000000000000000001224256054300155775ustar00rootroot00000000000000erlang-bear-0.8.0+dfsg/test/bear_test.erl000066400000000000000000000335501224256054300202610ustar00rootroot00000000000000%%% %%% Copyright 2013, Rodolphe Quiedeville %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% http://www.apache.org/licenses/LICENSE-2.0 %%% %%% Unless required by applicable law or agreed to in writing, software %%% distributed under the License is distributed on an "AS IS" BASIS, %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%% ==================================================================== %%% file : bear_test.erl %%% @author : Rodolphe Quiedeville %%% @doc %%% Unit test for functions defined in bear.erl %%% @end %%% ==================================================================== -module(bear_test). -compile(export_all). -record(scan_result, {n=0, sumX=0, sumXX=0, sumInv=0, sumLog, max, min}). -record(scan_result2, {x2=0, x3=0, x4=0}). -include_lib("eunit/include/eunit.hrl"). -define(PRECISION_DIGIT, 6). get_statistics_1_empty_test() -> %% get_statistics/1 %% Empty set of values Percentile = [{50, 0.0},{75, 0.0},{90, 0.0},{95, 0.0},{99, 0.0},{999, 0.0}], Stats = bear:get_statistics([]), ?assertEqual({min, 0.0}, lists:keyfind(min, 1, Stats)), ?assertEqual({max, 0.0}, lists:keyfind(max, 1, Stats)), ?assertEqual({arithmetic_mean, 0.0}, lists:keyfind(arithmetic_mean, 1, Stats)), ?assertEqual({geometric_mean, 0.0}, lists:keyfind(geometric_mean, 1, Stats)), ?assertEqual({harmonic_mean, 0.0}, lists:keyfind(harmonic_mean, 1, Stats)), ?assertEqual({median, 0.0}, lists:keyfind(median, 1, Stats)), ?assertEqual({variance, 0.0}, lists:keyfind(variance, 1, Stats)), ?assertEqual({standard_deviation, 0.0}, lists:keyfind(standard_deviation, 1, Stats)), ?assertEqual({skewness, 0.0}, lists:keyfind(skewness, 1, Stats)), ?assertEqual({kurtosis, 0.0}, lists:keyfind(kurtosis, 1, Stats)), ?assertEqual({percentile, Percentile}, lists:keyfind(percentile, 1, Stats)), ?assertEqual({histogram, [{0,0}]}, lists:keyfind(histogram, 1, Stats)), ?assertEqual({n, 0}, lists:keyfind(n, 1, Stats)). get_statistics_1_regular_test() -> %% get_statistics/1 %% Non empty set of values Percentile = [{50, -10},{75, 23},{90, 43},{95, 46},{99, 50},{999, 50}], Stats = bear:get_statistics(sample1()), {geometric_mean, Geometric} = lists:keyfind(geometric_mean, 1, Stats), {harmonic_mean, Harmonic} = lists:keyfind(harmonic_mean, 1, Stats), {variance, Variance} = lists:keyfind(variance, 1, Stats), {standard_deviation, StandardDeviation} = lists:keyfind(standard_deviation, 1, Stats), {kurtosis, Kurtosis} = lists:keyfind(kurtosis, 1, Stats), {skewness, Skewness} = lists:keyfind(skewness, 1, Stats), ?assertEqual({min, -49}, lists:keyfind(min, 1, Stats)), ?assertEqual({max, 50}, lists:keyfind(max, 1, Stats)), ?assertEqual({arithmetic_mean, -1.66}, lists:keyfind(arithmetic_mean, 1, Stats)), ?assertEqual(true, approx(4.08326, Geometric)), ?assertEqual(true, approx(54.255629738, Harmonic)), ?assertEqual({median, -10}, lists:keyfind(median, 1, Stats)), ?assertEqual(true, approx(921.0453061, Variance)), ?assertEqual(true, approx(30.348728, StandardDeviation)), ?assertEqual(true, approx(0.148722, Skewness)), ?assertEqual(true, approx(-1.2651687, Kurtosis)), ?assertEqual({percentile, Percentile}, lists:keyfind(percentile, 1, Stats)), ?assertEqual({histogram, [{-20,16},{11,16},{41,12},{71,6}]}, lists:keyfind(histogram, 1, Stats)), ?assertEqual({n, 50}, lists:keyfind(n, 1, Stats)). get_statistics_2_1_test() -> %% get_statistics/2 %% First set of values is empty Stats = bear:get_statistics(lists:seq(1,10), []), ?assertEqual(0.0, Stats). get_statistics_3_test() -> %% get_statistics/2 %% Second set of values is empty Stats = bear:get_statistics([], lists:seq(1,10)), ?assertEqual(0.0, Stats). get_statistics_4_test() -> %% get_statistics/2 %% Two set of values with different sizes Stats = bear:get_statistics(lists:seq(1,10),lists:seq(1,20)), ?assertEqual(0.0, Stats). get_statistics_5_test() -> %% get_statistics/2 %% Two set of values are valid Stats = bear:get_statistics(lists:seq(0,10),lists:seq(4,24,2)), ?assertEqual({covariance, 20.0}, lists:keyfind(covariance, 1, Stats)), ?assertEqual({tau, 1.0}, lists:keyfind(tau, 1, Stats)), ?assertEqual({rho, 1.0}, lists:keyfind(rho, 1, Stats)), ?assertEqual({r, 1.0}, lists:keyfind(r, 1, Stats)). scan_values_test() -> ?assertEqual(#scan_result{n=8}, bear:scan_values([], #scan_result{n=8})), ?assertEqual(#scan_result{n=1,sumX=1,sumXX=1,sumInv=1.0,sumLog=0.0,max=1,min=1}, bear:scan_values([1])), ?assertEqual(#scan_result{n=4,sumX=10,sumXX=30,sumInv=2.083333333333333,sumLog=3.1780538303479453,max=4,min=1}, bear:scan_values([1,3,2,4])). scan_values2_test() -> ?assertEqual(#scan_result{n=8}, bear:scan_values2([], 3, #scan_result{n=8})), ?assertEqual(#scan_result2{x2=6.6875,x3=-13.359375,x4=28.07421875}, bear:scan_values2([4,3,5], #scan_result{n=8,sumX=42})). revsort_test() -> ?assertEqual([], bear:revsort([])), ?assertEqual([4,3,2], bear:revsort([3,2,4])). arithmetic_mean_test() -> ?assertEqual(10.0, bear:arithmetic_mean(#scan_result{n=4, sumX=40})). geometric_mean_test() -> ?assertEqual(25.790339917193062, bear:geometric_mean(#scan_result{n=4, sumLog=13})). harmonic_mean_test() -> ?assertEqual(0, bear:harmonic_mean(#scan_result{n=100, sumInv=0})), ?assertEqual(10.0, bear:harmonic_mean(#scan_result{n=100, sumInv=10})). percentile_test() -> ?assertEqual(3, bear:percentile([1,2,3,4,5], #scan_result{n=5},0.5)), ?assertEqual(5, bear:percentile([1,2,3,4,5], #scan_result{n=5},0.95)). variance_test() -> ?assertEqual(7.0, bear:variance(#scan_result{n=7},#scan_result2{x2=42})). std_deviation_test() -> ?assertEqual(3.0, bear:std_deviation(#scan_result{n=10},#scan_result2{x2=81})). skewness_test() -> ?assertEqual(0.0, bear:skewness(#scan_result{n=10},#scan_result2{x2=0,x3=81})), ?assertEqual(3.0, bear:skewness(#scan_result{n=10},#scan_result2{x2=81,x3=810})). kurtosis_test() -> ?assertEqual(0.0, bear:kurtosis(#scan_result{n=10},#scan_result2{x2=0,x4=81})), ?assertEqual(-2.0, bear:kurtosis(#scan_result{n=10},#scan_result2{x2=81,x4=810})). update_bin_1_test() -> %% with empty dict Dict = dict:new(), C = bear:update_bin(4, [4], Dict), ?assertEqual(1, dict:fetch(4, C)). get_covariance_exceptions_test() -> %% Array 1 is too short ?assertEqual(0.0, bear:get_covariance([], [2,1,2,3,4,5,6])), %% Array 2 is too short ?assertEqual(0.0, bear:get_covariance([1,2,3,4,5,6], [])), %% diffenrent arry length ?assertEqual(0.0, bear:get_covariance([1,2,3,4,5,6], [1,2,3,4,5,6,7])). get_covariance_regular_test() -> %% Usual case %% Result is not the same as R compute, R use an unbiased estimate %% http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Covariance ?assertEqual(true, approx(170.813599, bear:get_covariance(sample1(),sample2()))). ranks_of_test() -> ?assertEqual([4.0,3.0,1.0,2.0], bear:ranks_of([3,4,15,6])). get_pearson_correlation_exceptions_test() -> ?assertEqual(0.0, bear:get_pearson_correlation([], 42)), ?assertEqual(0.0, bear:get_pearson_correlation(42, [])), ?assertEqual(0.0, bear:get_pearson_correlation(lists:seq(1,10), lists:seq(1,11))), ?assertEqual(1.0, bear:get_pearson_correlation(lists:seq(1,10), lists:seq(1,10))), ?assertEqual(1.0, bear:get_pearson_correlation(lists:seq(0,10), lists:seq(5,15))). get_pearson_correlation_regular_test() -> %% Target is calculate by R ?assertEqual(true, approx(0.2068785, bear:get_pearson_correlation(sample1(), sample2()))). get_pearson_correlation_nullresult_test() -> %% The two series do not correlate A = [-1,-0.5,0,0.5,1], B = [1,0.25,0,0.25,1], ?assertEqual(0.0, bear:get_pearson_correlation(A, B)). round_bin_test() -> ?assertEqual(10, bear:round_bin(10)), ?assertEqual(10, bear:round_bin(10, 5)), ?assertEqual(42, bear:round_bin(15, 42)), ?assertEqual(45, bear:round_bin(42, 15)). get_bin_width_test() -> ?assertEqual(1, bear:get_bin_width(0, 10)), ?assertEqual(22, bear:get_bin_width(10.0, 4.0)). get_bin_count_test() -> ?assertEqual(3, bear:get_bin_count(9, 15, 3)), ?assertEqual(4, bear:get_bin_count(10.2, 20.2, 4)). get_kendall_correlation_exceptions_test()-> ?assertEqual(0.0, bear:get_kendall_correlation([], [])), ?assertEqual(0.0, bear:get_kendall_correlation([], [1,2,3,4,5,6,7])), ?assertEqual(0.0, bear:get_kendall_correlation([1,2,3,4,5,6,7],[])), ?assertEqual(0.0, bear:get_kendall_correlation(lists:seq(1,10),lists:seq(1,11))). get_kendall_correlation_regular_test()-> Kendall = bear:get_kendall_correlation(sample1(order), sample2(order)), ?assertEqual(true, approx(0.9787755, Kendall)). kendall_correlation_test()-> Kendall = bear:kendall_correlation(sample1(order), sample2(order)), ?assertEqual(true, approx(0.9787755, Kendall)). get_spearman_correlation_exceptions_test()-> ?assertEqual(0.0, bear:get_spearman_correlation([], [])), ?assertEqual(0.0, bear:get_spearman_correlation([], [1,2,3,4,5,6,7])), ?assertEqual(0.0, bear:get_spearman_correlation([1,2,3,4,5,6,7],[])), ?assertEqual(0.0, bear:get_spearman_correlation(lists:seq(1,10),lists:seq(1,11))). get_spearman_correlation_regular_test()-> ?assertEqual(true, approx(0.997888, bear:get_spearman_correlation(sample1(order), sample2(order)))). math_log_test() -> ?assertEqual(1, bear:math_log(0)), ?assertEqual(1.0, bear:math_log(0.0)), ?assertEqual(true, approx(3.737669618283368, bear:math_log(42))). inverse_test() -> ?assertEqual(0, bear:inverse(0)), ?assertEqual(0.0, bear:inverse(0.0)), ?assertEqual(0.5, bear:inverse(2)). get_hist_bins_test() -> ?assertEqual([4], bear:get_hist_bins(1, 4, 5, 10)). tied_ordered_ranking_test() -> ?assertEqual([3,2,1], bear:tied_ordered_ranking([], [], [1,2,3])). kendall_right_off_test() -> %% empty array ?assertEqual("654321", bear:kendall_right_of([],"123456")). tied_add_prev_test() -> ?assertEqual([{2.5,5},{2.5,5},{2.5,5},{2.5,5},{2,3}], bear:tied_add_prev([{2, 3}], {[1,2,3,4], 5})). tied_rank_worker_test() -> ?assertEqual([{2.0,5},{2.0,5},{2.0,5},{2.0,5}], bear:tied_rank_worker([], [{2.0,5}], {[1,2,3], 5})), ?assertEqual([{2.0,5},{2.0,5},{2.0,5},{2.0,5},{2.0,5},{2.0,5}], bear:tied_rank_worker([{2.0,5},{2.0,5}], [{2.0,5}], {[1,2,3], 5})). perc_test() -> ?assertEqual(14, bear:perc(36, 40)), ?assertEqual(5, bear:perc(900, 5)), ?assertEqual(5, bear:perc(0.9, 5)). get_statistics_subset_nev_test() -> %% Not enough values case ?assertEqual([], bear:get_statistics_subset([1,2], [])). get_statistics_subset_regular_test() -> %% Regular case ?assertEqual([{max, 50},{min, -49}], bear:get_statistics_subset(sample1(), [max,min])). subset_test() -> Stats = bear:get_statistics(test_values()), match_values(Stats). full_subset_test() -> Stats = bear:get_statistics(test_values()), match_values2(Stats). negative_test() -> %% make sure things don't blow up with a negative value Values = [1,-1,-2,3,3,4,5,6,7], [{min, -2}] = bear:get_statistics_subset(Values, [min]). negative2_test() -> %% make sure things don't blow up with a negative value Values = [-1,-1,-2,-2,-3,-5,-6,-10], [{min, -10}] = bear:get_statistics_subset(Values, [min]). match_values([H|T]) -> Res = bear:get_statistics_subset(test_values(), [mk_item(H)]), Res = [H], match_values(T); match_values([]) -> ok. mk_item({percentile, Ps}) -> {percentile, [P || {P,_} <- Ps]}; mk_item({K, _}) -> K. match_values2(Stats) -> Items = [mk_item(I) || I <- Stats], Stats = bear:get_statistics_subset(test_values(), Items), ok. test_values() -> [1,1,1,1,1,1,1, 2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9]. negative_values() -> %% All values are negative [-1,-1,-1,-1,-1,-1,-1, -2,-2,-2,-2,-2,-2,-2, -3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3, -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4, -5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5, -6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6,-6, -7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7,-7, -8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8,-8, -9,-9,-9,-9,-9,-9,-9]. between(Value, Low, High) -> (Value >= Low) and (Value =< High). approx(Target, Value) -> High = Target + math:pow(10, - ?PRECISION_DIGIT), Low = Target - math:pow(10, - ?PRECISION_DIGIT), case (Value > Low) and (Value < High) of true -> true; _ -> Value end. check_sample_test() -> ?assertEqual(50, length(sample1())), ?assertEqual(50, length(sample1(order))), ?assertEqual(50, length(sample2())), ?assertEqual(50, length(sample2(order))). sample1(X) when X == order -> lists:sort(sample1()). sample2(X) when X == order -> lists:sort(sample2()). sample1() -> %% datas from file bear/samples/data.csv %% first column X [-16,-18,-47,22,-18,36,25,49,-24,15,36,-10,-21,43,-35,1,-24,10,33,-21,-18,-36,-36,-43,-37,-10,23,50,31,-49,43,46,22,-43,12,-47,15,-14,6,-31,46,-8,0,-46,-16,-22,6,10,38,-11]. sample2() -> %% datas from file bear/samples/data.csv %% second column Y [33,20,-35,16,-19,8,25,3,4,10,36,-20,-41,43,28,39,-30,3,-47,-23,17,-6,-50,16,-26,-49,8,-31,24,16,32,27,-19,-32,-17,1,-37,25,-50,-32,-42,-22,25,18,-34,-37,7,-13,16,10].