# Autogenerated with SMOP 0.27.8
from __future__ import division
from smop.core import *
# 

    
def mybench(*args):
    varargin = cellarray(args)
    # res = mybench('noOfRepeats', 3,...
#                     'normalize',true,...
#                     'onlyTests',[],...
#                     'imagep',true)
#
# Benchmark script for MATLAB and Octave.
# Tested on Matlab 2009a and Octave 3.2.2 for Windows.
#
# Execution time of basic matrix manipulation function is tested along with 
# integration, solving nonlinear equation, image processing functions ( if
# avaliable), saveing/loading matrices to a file system, for loop,
# binary operation,etc. In total 27
# tests are performed (less if image processing functions not avaliable).
#
# All results are normilized against the results obtained
# using MATLAB 7.4.0.287 (R2007a) on Intel Mac OS X 10.4.11 (Intel Core Duo
# 2GHz, 2GB RAM)
#
# At the end, arithmetic and geometric means of the times obtained are
# calculated. All results obtained are stored in a txt file named
# results_<matlab/octave version>.txt.
#
# INPUT
#  noOfRepeats - int - number of times each test is executed (default 3)
#  normalize - boolean - normalize results (default true).
#  onlyTests - int vector - do only tests given (default [], i.e. do all tests) 
#
# OUTPUT
# res - struct -   normalized geometric mean . 
#
# EXAMPLES
# res = mybench(); #perform all tests with default settings.
# res = mybench('noOfRepeats',10); #perform all tests 10 times.
# res = mybench('onlyTests',[1,5,8]); #perform only tests 1,5 and 8.
# res = mybench('noOfRepeats', 1,'normalize',false); # repeat 1 time 
#                                               #each tests and do not 
#                                               #normalize results.
#
# KNOWN_ISSUES
# Solving nonlinear equation produces info about termination - don't worry.
# 
# Site: http:\\shortrecipes.blogspot.com
# Date: Nov 2009
#
    global IS_OCTAVE IS_IMAGE_PROCESSING
    
    #DEFAULT INPUT PARAMETERS.
    conf=struct("noOfRepeats",3,"normalize",true,"imagep",true,"onlyTests",[])
# mybench.m:49
    conf=getargs(conf,varargin)
# mybench.m:56
    IS_OCTAVE=exist("OCTAVE_VERSION","builtin") > 0
# mybench.m:58
    IS_IMAGE_PROCESSING=copy(false)
# mybench.m:59
    NO_REPETITIONS=conf.noOfRepeats
# mybench.m:60
    NORMALIZE_TIMES=conf.normalize
# mybench.m:61
    if exist("imrotate","file") > 0 and exist("imresize","file") > 0 and exist("imerode","file") > 0 and conf.imagep == true:
        disp("Image processing toolbox found")
        IS_IMAGE_PROCESSING=copy(true)
# mybench.m:66
    
    
    if conf.noOfRepeats < 1:
        conf.noOfRepeats = copy(1)
# mybench.m:70
    
    
    clc
    mytests=getBenchmarkTests()
# mybench.m:75
    noOftests=length(mytests)
# mybench.m:76
    
    moVersio=strrep(version()," ","_")
# mybench.m:79
    outFileName="foo.txt"
# mybench.m:80
    fid=fopen(outFileName,"w")
# mybench.m:81
    if NORMALIZE_TIMES:
        fprintf(fid,"%s\t%s\t%s\n",cat("Name_",moVersio),"Time","Norm_time")
    else:
        fprintf(fid,"%s\t%s\n",cat("Name_",moVersio),"Time_[s]")
    
    
    avarage_time=0
# mybench.m:89
    times_vector=matlabarray([])
# mybench.m:91
    times_vector1=matlabarray([])
# mybench.m:92
    
    
    if isempty(conf.onlyTests):
        doTheseTests=arange(1,noOftests)
# mybench.m:95
    else:
        doTheseTests=conf.onlyTests
# mybench.m:97
        noOftests=length(conf.onlyTests)
# mybench.m:98
    
    
    #loop over tests
    for i in doTheseTests.reshape(-1):
        #display some info
        fprintf(1,"Execute test %d/%d -  %s\n",i,noOftests,mytests[i].name)
        if IS_OCTAVE:
            fflush(stdout)
        try:
            #get input for a give test
            x=mytests[i].input()
# mybench.m:111
            cumulative_time=0
# mybench.m:114
            cumulative_time1=0
# mybench.m:115
            goldResult=1
# mybench.m:116
            for ii in arange(1,NO_REPETITIONS).reshape(-1):
                fprintf(1,"%d ",ii)
                if IS_OCTAVE:
                    fflush(stdout)
                t0=tic()
# mybench.m:122
                mytests[i].test(x)
                t1=toc(t0)
# mybench.m:124
                if isfield(mytests[i],"goldResult") and NORMALIZE_TIMES == true:
                    goldResult=mytests[i].goldResult
# mybench.m:127
                cumulative_time=cumulative_time + t1 / goldResult
# mybench.m:130
                cumulative_time1=cumulative_time1 + t1
# mybench.m:131
            avarage_time=cumulative_time / NO_REPETITIONS
# mybench.m:134
            avarage_time1=cumulative_time1 / NO_REPETITIONS
# mybench.m:135
            times_vector[end() + 1]=avarage_time
# mybench.m:136
            times_vector1[end() + 1]=avarage_time1
# mybench.m:137
        finally:
            pass
        #some postprocessing if defined
        if isfield(mytests[i],"post"):
            mytests[i].post()
        #display some info
        fprintf(1,"\n\tTime %.2f [s]\n",avarage_time1)
        if NORMALIZE_TIMES == true:
            fprintf(1,"\tNormalized time %.2f \n",avarage_time)
        fprintf(1,"\n")
        if IS_OCTAVE:
            fflush(stdout)
        if NORMALIZE_TIMES:
            fprintf(fid,"%s\t%f\t%f\n",mytests[i].name,avarage_time1,avarage_time)
        else:
            fprintf(fid,"%s\t%f\n",mytests[i].name,avarage_time1)
    
    times_product=prod(times_vector)
# mybench.m:172
    times_mean=mean(times_vector)
# mybench.m:173
    times_geometric_mean=times_product ** (1 / length(times_vector))
# mybench.m:174
    times_product1=prod(times_vector1)
# mybench.m:176
    
    times_mean1=mean(times_vector1)
# mybench.m:177
    times_geometric_mean1=times_product1 ** (1 / length(times_vector1))
# mybench.m:178
    res.norm_geometric_mean = copy(times_geometric_mean)
# mybench.m:180
    res.norm_arithmetic_mean = copy(times_mean)
# mybench.m:181
    res.norm_min = copy(min(times_vector))
# mybench.m:182
    res.norm_max = copy(max(times_vector))
# mybench.m:183
    fprintf(1,"\n\t --- SUMMARY ---\n")
    
    
    fprintf(1,"\n\tMean: geometric %.3f [s], arithmetic %.3f [s]",times_geometric_mean1,times_mean1)
    fprintf(1,"\n\tMin %.3f [s], Max %.3f [s]\n\n",min(times_vector1),max(times_vector1))
    if NORMALIZE_TIMES == true:
        fprintf(1,"\tNormalized Mean: geometric %.3f, arithmetic %.3f",times_geometric_mean,times_mean)
        fprintf(1,"\n\tNormalized Min %.3f [s], Max %.3f [s]\n\n",min(times_vector),max(times_vector))
    
    if IS_OCTAVE:
        fflush(stdout)
    
    
    if NORMALIZE_TIMES:
        fprintf(fid,"%s\t%f\t%f\n","Geom_mean",times_geometric_mean1,times_geometric_mean)
    else:
        fprintf(fid,"%s\t%f\t%f\n","Geom_mean",times_geometric_mean1)
    
    
    fclose(fid)
    disp("")
    disp(cat("End of test. File ",outFileName," was created."))
    
    #do some clean up
    if exist("out_gray.png"):
        delete("out_gray.png")
    
    if exist("out_1.png"):
        delete("out_1.png")
    
    if exist("out_mtx"):
        delete("out_mtx")
    
    if exist("out_mtx.mat"):
        delete("out_mtx.mat")
    
    if exist("dlm.txt"):
        delete("dlm.txt")
    
    
    clear("IS_OCTAVE","IS_IMAGE_PROCESSING")
    ########################## FUNCTIONS **********************
    
    return res
    
@function
def getBenchmarkTests():
    nargin = getBenchmarkTests.nargin
    #the cell with tests name, test functions and input params.
#Each tests has the form of a structure with filelds 'name', 'test',
#'input', and optional 'post' nad 'goldResult' fields.
#'name' is a name that you want to give to  your test.
#'test' is an anonymous function or a function handler. The execution time
# of this function is measured.
#'input'  anonymous function that provides input data to a test. The time
# of this function is not measured.
# 'post'  anonymous function that can do some postprocessing, e.g. cleanup.
# the time of 'post' funciton is not measured
# 'goldResult' is a result in seconds obtaiend on my computer. This times
# is used for the normalization of time scores. 
#
#
    global IS_OCTAVE,IS_IMAGE_PROCESSING
    
    s=cellarray([])
# mybench.m:243
    
    #    'input', @()rand(600),'goldResult',4.20);
    
    s[end() + 1]=struct("name","rand","test",lambda x: rand(x),"input",lambda : 4000,"goldResult",1.12)
# mybench.m:249
    s[end() + 1]=struct("name","randn","test",lambda x: randn(x),"input",lambda : 4000,"goldResult",0.58)
# mybench.m:255
    s[end() + 1]=struct("name","primes","test",lambda x: primes(x),"input",lambda : 10000000.0,"goldResult",0.74)
# mybench.m:261
    s[end() + 1]=struct("name","fft2","test",lambda x: fft2(x),"input",lambda : rand(3000),"goldResult",2.28)
# mybench.m:264
    
    #    'goldResult',2.979296);
    
    s[end() + 1]=struct("name","square","test",lambda x: x ** 2,"input",lambda : rand(1000),"goldResult",1.35)
# mybench.m:270
    s[end() + 1]=struct("name","inv","test",lambda x: inv(x),"input",lambda : rand(1000),"goldResult",0.87)
# mybench.m:273
    s[end() + 1]=struct("name","eig","test",lambda x: eig(x),"input",lambda : rand(1000),"goldResult",9.45)
# mybench.m:276
    s[end() + 1]=struct("name","qr","test",lambda x: qr(x),"input",lambda : rand(1000),"goldResult",0.79)
# mybench.m:279
    s[end() + 1]=struct("name","schur","test",lambda x: schur(x),"input",lambda : rand(600),"goldResult",2.67)
# mybench.m:282
    s[end() + 1]=struct("name","roots","test",lambda x: roots(x),"input",lambda : rand(600,1),"goldResult",2.08)
# mybench.m:285
    s[end() + 1]=struct("name","binary","test",lambda x: eye(x) < 1,"input",lambda : 5000,"goldResult",0.51)
# mybench.m:288
    s[end() + 1]=struct("name","forLoop","test",lambda x: forLoop(x),"input",lambda : 200,"goldResult",0.06)
# mybench.m:293
    s[end() + 1]=struct("name","makeSparse","test",lambda x: sparse(x),"input",lambda : eye(5000),"goldResult",0.49)
# mybench.m:298
    s[end() + 1]=struct("name","multiplySparse","test",lambda x: sparse(x) * sparse(x),"input",lambda : eye(5000) * rand(1),"goldResult",0.98)
# mybench.m:303
    s[end() + 1]=struct("name","sLinearEq","test",lambda x: magic(x) / rand(1,x),"input",lambda : 2000,"goldResult",1.94)
# mybench.m:308
    
    #     @(x) solveNonLinearEq(),'input', @() NaN ,'goldResult',0.07);
    
    s[end() + 1]=struct("name","saveLoadMtx","test",lambda x: saveLoadMtx(x),"input",lambda : rand(1000),"goldResult",0.93)
# mybench.m:316
    s[end() + 1]=struct("name","dlmwriteRead","test",lambda x: dlmwriteRead(x),"input",lambda : rand(500),"goldResult",5.03)
# mybench.m:319
    s[end() + 1]=struct("name","median","test",lambda x: median(x[:]),"input",lambda : rand(4000),"goldResult",3.32)
# mybench.m:322
    s[end() + 1]=struct("name","std","test",lambda x: std(x[:]),"input",lambda : rand(4000),"goldResult",0.84)
# mybench.m:325
    
    #     @() quadl (@(x) x .* sin (1 ./ x) .* sqrt (abs (1 - x)), 0, 3),...
   #    'input', @() NaN,'goldResult',0.038028);
    
    
    if IS_IMAGE_PROCESSING:
        s[end() + 1]=struct("name","doImgAndSaveAsPNG","test",lambda x: doImgAndSaveAsPNG(x),"input",lambda : rand(1500,1500,3),"post",lambda : pause(2),"goldResult",2.0)
# mybench.m:335
        s[end() + 1]=struct("name","imageToGray","test",lambda I: imageToGray(I),"input",lambda : imread("out_1.png"),"goldResult",0.56)
# mybench.m:340
        s[end() + 1]=struct("name","imageRotate","test",lambda I: imageRotate(I),"input",lambda : imread("out_gray.png"),"goldResult",2.94)
# mybench.m:344
        s[end() + 1]=struct("name","imresize","test",lambda I: imresize(I,1.2),"input",lambda : imread("out_gray.png"),"goldResult",1.24)
# mybench.m:348
        s[end() + 1]=struct("name","imageFilter","test",lambda I: imageFilter(I),"input",lambda : imread("out_gray.png"),"goldResult",0.2)
# mybench.m:352
        s[end() + 1]=struct("name","imageErode","test",lambda I: imageErode(I),"input",lambda : imread("out_gray.png"),"goldResult",0.46)
# mybench.m:356
        s[end() + 1]=struct("name","medfilt2","test",lambda I: medfilt2(I),"input",lambda : magic(2000),"goldResult",1.03)
# mybench.m:360
    
    
    # ADDITIONAL TEST FUNCTIONS
    return s
    
@function
def saveLoadMtx(out_mtx):
    nargin = saveLoadMtx.nargin
    save("out_mtx")
    clear("out_mtx")
    load("out_mtx")
    return
    
@function
def dlmwriteRead(x):
    nargin = dlmwriteRead.nargin
    dlmwrite("dlm.txt",x)
    dlmread("dlm.txt")
    return
    
@function
def forLoop(x):
    nargin = forLoop.nargin
    for i in arange(1,x).reshape(-1):
        for j in arange(1,x).reshape(-1):
            for k in arange(1,x).reshape(-1):
                i + j + k
    
    
    return
    
@function
def doImgAndSaveAsPNG(x):
    nargin = doImgAndSaveAsPNG.nargin
    #plot a surf and save it image png with 300DPI
	#f=figure;
	#set(f,'Visible','off');
	#surf(x);    
	#print(['-f',int2str(f)],'-dpng','-r200',['out_1.png']);
	#close(f)
    
    imwrite(x,"out_1.png")
    return
    
@function
def solveNonLinearEq():
    nargin = solveNonLinearEq.nargin
    x,fval,info=fsolve(equationsToSolve,cat([1],[1],[1],[1]),nargout=3)
# mybench.m:398
    return
    
@function
def equationsToSolve(x):
    nargin = equationsToSolve.nargin
    y[1]=- 2 * x[1] ** 2 + 3 * x[1] * x[2] + 4 * sin(x[2]) + log(x[3]) - 6
# mybench.m:401
    y[2]=3 * x[1] ** 2 - 2 * x[2] * x[2] ** 2 + 3 * cos(x[1]) + 4
# mybench.m:402
    y[3]=1 * x[1] ** 2 - 2 * x[1] * x[2] * x[4] ** 2 + 3 * cos(x[1]) + 4
# mybench.m:403
    y[4]=1 * x[1] ** 2 - 2 * x[1] * x[2] * x[3] ** 2 + 3 * cos(x[4]) + 4
# mybench.m:404
    return y
    
@function
def imageToGray(I):
    nargin = imageToGray.nargin
    Igray=rgb2gray(I)
# mybench.m:408
    imwrite(Igray,"out_gray.png")
    return
    
@function
def imageRotate(I):
    nargin = imageRotate.nargin
    I2=imrotate(I,2)
# mybench.m:412
    return
    
@function
def imageFilter(I):
    nargin = imageFilter.nargin
    h=fspecial("sobel")
# mybench.m:415
    filteredI=imfilter(I,h)
# mybench.m:416
    return
    
@function
def imageErode(I):
    nargin = imageErode.nargin
    SE=eye(5)
# mybench.m:419
    erodedI=imerode(I,SE)
# mybench.m:420
    # Get input argumetns
    return
    
@function
def getargs(defs,varglist):
    nargin = getargs.nargin
    l=length(varglist)
# mybench.m:427
    if l == 0:
        return defs
    
    if mod(l,2) != 0:
        disp(" !!! Odd number of parameters !!!")
        defs=cellarray([])
# mybench.m:431
        return defs
    
    varnames=cellarray([varglist[1:2:l]])
# mybench.m:434
    varvalues=cellarray([varglist[2:2:l]])
# mybench.m:435
    given_vars=zeros_(1,l / 2)
# mybench.m:436
    for i in arange(1,l / 2,1).reshape(-1):
        existss=isfield(defs,varnames[i])
# mybench.m:438
        given_vars[i]=existss
# mybench.m:439
    
    
    if min(given_vars) == 0:
        disp("!!! No such parameter(s):")
        disp(varnames[not given_vars])
        defs=cellarray([])
# mybench.m:445
        return defs
    
    for i in arange(1,l / 2,1).reshape(-1):
        setattr(defs,varnames[i],varvalues[i])
# mybench.m:449
    
    return defs
