コード例 #1
0
    def generate_suggestion(self):
        """Function is given a set of user points and generates a suggestion based on the algorithm
        Engage after user clicks box -- for now..."""
        self.phi = [sum(x) / len(x) for x in zip(*self.belief.states)]
        # Sample set of points to iterate over
        self.best_points_idx, self.best_points_phi = Main.find_similar_points(self.guess_beta, self.phi,
                                                                              self.p_sample, self.suggested)
        # print(list(self.best_points_phi))

        # Generate new suggestion using Julia function call
        suggest = Main.find_next_action(list(self.user_points), self.best_points_phi, self.observe_beta,
                                        self.final_beta, self.user, self.num_guess)

        self.suggested.append(suggest)
        self.num_guess -= 1  # Decrement step counter
        print(suggest)
        # Find index that the algorithm suggested
        # If the algorithm chooses to wait, then don't publish anything
        if suggest != "wait":
            ans = self.guess_points[int(suggest)]
            print("The ans is ", ans)
            # Publish to ROS
        else:
            ans = "wait"
        # self.suggest_pub.publish(ans)
        return ans
コード例 #2
0
def test_pandamodels_installation():
    
    from julia import Main
    from julia import Pkg
    from julia import Base

    if Base.find_package("PandaModels"):  
        # remove PandaModels to reinstall it
        Pkg.rm("PandaModels")
        Pkg.resolve()

    else:
        print("PandaModels is not installed yet!")  
      
    Pkg.Registry.update()
    Pkg.add("PandaModels")  
    Pkg.build()
    Pkg.resolve()
    print("PandaModels is added to julia packages")

    try:
        Main.using("PandaModels")
        print("using PandaModels in its base mode!")
    except ImportError:
        raise ImportError("cannot use PandaModels in its base mode")
コード例 #3
0
def JuliaSimulation(sim,
                    simulate=False,
                    useBrownians=False,
                    times=None,
                    nPaths=None,
                    seed=None,
                    timeInterpolation=None):
    if not isinstance(sim, McSimulation):
        raise NotImplementedError(
            'Implementation of JuliaSimulation for %s required.' %
            str(type(sim)))
    model = JuliaModel(sim.model)
    # check for manual parameters
    if times is None: times = sim.times
    if nPaths is None: nPaths = sim.nPaths
    if seed is None: seed = sim.seed
    if timeInterpolation is None: timeInterpolation = sim.timeInterpolation
    #
    if simulate:
        if useBrownians:
            # Julia is column-major layout
            return Main.McSimulationWithBrownians(model, times,
                                                  sim.dW.transpose(2, 1, 0),
                                                  timeInterpolation)
        else:
            return Main.McSimulation(model, times, nPaths, seed,
                                     timeInterpolation)
    else:  # do not use this with manual inputs
        # Julia is column-major layout
        return Main.McSimulation(model, times, nPaths, seed, timeInterpolation,
                                 sim.dW.transpose(2, 1, 0),
                                 sim.X.transpose(2, 1, 0))
    return None
コード例 #4
0
ファイル: run_robot.py プロジェクト: pjssilva/Robot-vaccine
def save_result(basic_prm, cities_data, target, filename):
    """Save the result of a run for further processing.
    """
    cities_names = cities_data.index
    n_cities = len(cities_names)

    var_s = get_jump_variable('s')
    var_e = get_jump_variable('e')
    var_i = get_jump_variable('i')
    var_r = get_jump_variable('r')
    var_ei = get_jump_variable('ei')
    var_ir = get_jump_variable('ei')
    var_v = get_jump_variable('v')
    var_V = get_jump_variable('V')
    icupop = Julia.prm.icupop / Julia.prm.tinf
    mean_icu = (cities_data["rho_min"][0] +
                (cities_data["rho_max"][0] - cities_data["rho_min"][0]) *
                cities_data["intercept"][0])
    Julia.eval("rt = reshape(expand(value.(m[:rt]), prm), (:,))")
    n = len(Julia.s[0, 0, :])
    df = []

    for p in range(var_s.shape[0]):
        for d in [0, 1, 2]:
            df.append(["s", p, d] + list(var_s[p, d, :]))
            df.append(["e", p, d] + list(var_e[p, d, :]))
            df.append(["i", p, d] + list(var_i[p, d, :]))
            df.append(["r", p, d] + list(var_r[p, d, :]))
        for d in [0, 1]:
            df.append(["ei", p, d] + list(var_ei[p, d, :]))
            df.append(["ir", p, d] + list(var_ir[p, d, :]))
            df.append(["v", p, d] + list(var_v[p, d, :]))
        df.append(["icu_demand", p, -1] +
                  list(mean_icu / basic_prm["time_icu"] * var_V[0, p, :]))

    df.append(["rt", -1, -1] + list(Julia.rt))

    # Information on ICU
    c = cities_names[0]
    icu_capacity = cities_data.loc[c, "population"] * cities_data.loc[
        c, "icu_capacity"]
    df.append(["icu_capacity", -1, -1] + list(icu_capacity * np.ones(n)))
    icu_target = icu_capacity * target.loc[c, :]
    df.append(["target_icu", -1, -1] + list(icu_target))
    rho_icu = SimpleTimeSeries(*cities_data.iloc[0, 7:-2])
    confidence = cities_data.loc[c, "confidence"]
    mean_icu, upper_icu = rho_icu.get_upper_bound(n, confidence)
    df.append(["mean_rho_icu", -1, -1] + list(mean_icu))
    df.append(["upper_rho_icu", -1, -1] + list(upper_icu))
    # mean_icu = cities_data.loc[c, "time_icu"] / basic_prm["tinf"] * mean_icu * cities_data.loc[c, "population"] * Julia.i[i, :]
    # df.append(["mean_used_icu", -1] + list(mean_icu))
    # upper_icu = cities_data.loc[c, "time_icu"] / basic_prm["tinf"] * upper_icu * cities_data.loc[c, "population"] * Julia.i[i, :]
    # df.append(["upper_used_icu"] + list(upper_icu))

    df = pd.DataFrame(df,
                      columns=["Variable", "Subpopulation", "Dose"] +
                      list(range(len(Julia.s[0, 0, :]))))
    df.set_index(["Variable", "Subpopulation", "Dose"], inplace=True)
    df.to_csv(filename)
    return df
コード例 #5
0
ファイル: embedding.py プロジェクト: JunweiSUN/AutoGRL
def spectral(data, name, embedding_dim=128):
    try:
        result = load_embedding(name, 'spectral')
        return result
    except FileNotFoundError:
        print(
            f'cache/feature/spectral_{name}.pt not found! Regenerating it now')

    from julia.api import Julia
    jl = Julia(compiled_modules=False)
    from julia import Main
    Main.include(f'{CWD}/norm_spec.jl')
    print('Setting up spectral embedding')

    if data.setting == 'inductive':
        N = data.num_train_nodes
        edge_index = to_undirected(data.train_edge_index,
                                   num_nodes=data.num_train_nodes)
    else:
        N = data.num_nodes
        edge_index = to_undirected(data.edge_index, num_nodes=data.num_nodes)

    np_edge_index = np.array(edge_index.T)
    row, col = edge_index
    adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
    adj = adj.to_scipy(layout='csr')

    result = torch.tensor(Main.main(adj, embedding_dim)).float()
    save_embedding(result, name, 'spectral')
    return result
コード例 #6
0
ファイル: call.py プロジェクト: btarroja/REISE.jl
def scenario_julia_call(scenario_info, start_index, end_index):
    """
    Starts a Julia engine, runs the add_path file to load Julia code.
    Then, loads the data path and runs the scenario.

    :param dict scenario_info: scenario information.
    :param int start_index: start index.
    :param int end_index: end index.
    """

    from julia.api import Julia
    jl = Julia(compiled_modules=False)
    from julia import Main
    from julia import REISE

    interval = int(scenario_info['interval'].split('H', 1)[0])
    n_interval = int((end_index - start_index + 1) / interval)

    input_dir = os.path.join(const.EXECUTE_DIR,
                             'scenario_%s' % scenario_info['id'])
    output_dir = os.path.join(const.EXECUTE_DIR,
                              'scenario_%s/output/' % scenario_info['id'])

    REISE.run_scenario(interval=interval,
                       n_interval=n_interval,
                       start_index=start_index,
                       inputfolder=input_dir,
                       outputfolder=output_dir)
    Main.eval('exit()')
コード例 #7
0
    def find_minimum_production(self, coords, opt_param_dict):
        """
        Find the minimum corresponding to the coords.

        Parameters
        ----------
        coords : np.ndarray
            Coordinates for which we want to find the corrsponding minima
        """
        nls = Main.NewtonLinesearch(self.interfaced_potential, coords,
                                    opt_param_dict["tol"])
        mxd = Main.Mixed_Descent(
            self.interfaced_potential,
            Main.CVODE_BDF(),
            nls,
            coords,
            opt_param_dict["T"],
            opt_param_dict["rtol"],
            opt_param_dict["conv_tol"],
            opt_param_dict["tol"],
        )
        try:
            mxd.run_b(mxd, opt_param_dict["n_steps"])
        except:
            return None
        return (
            mxd.optimizer.x0,
            mxd.converged,
            mxd.n_g_evals,
            mxd.iter_number,
            mxd.n_h_evals,
        )
コード例 #8
0
def main():
    Main.include("napier.jl")
    for _ in range(10):
        start = time.time()
        Main.count_upto_one()
        end = time.time()
        print(end - start)
コード例 #9
0
def script():

    print('in script')

    #############Load Vars#############
    #If we saved the vars in MATLAB then we load them here.
    a = np.load('a.npy')
    b = np.load('b.npy')

    #If you want a as ints or floats for your julia scripts use the conversions below,
    #(provided these inputs are single no's when defined and converted to numpy arrays in MATLAB e.g. "a=1")
    #a=int(a);
    #a=float(a);

    #############Python bit#############
    #Testing we can actually use python (not needed)
    c = np.add(a, b)

    print('NumPy Sum result')
    print(c)

    #############Julia bit#############
    #Compute something in Julia (from a module)
    from julia import Main
    print('Make sure you cd to correct dir here')
    Main.include(string(pwd(), "SumArrays.jl"))
    d = Main.SumArrays(a, b)

    print('Julia Sum result')
    print(d)

    #############Save bit#############
    #Now save as MATLAB matricies.
    scipy.io.savemat('PythonOutput.mat', dict(a=a, b=b, c=c, d=d))
コード例 #10
0
    def get_indiv_fitness(self, index):
        Main.ea_step = index[0]
        Main.pop_index = index[1]
        Main.eval(
            'fitness = DataMod.get_indiv_fitness(data, ea_step, pop_index)')

        return Main.fitness
コード例 #11
0
def test_pandamodels_dev_mode(): 
    
    from julia import Main
    from julia import Pkg
    from julia import Base

    if Base.find_package("PandaModels"):  
        # remove PandaModels to reinstall it
        Pkg.rm("PandaModels")
        Pkg.resolve()
        
    Pkg.Registry.update()
    Pkg.add("PandaModels")  
    print("installing dev mode is a slow process!")  
    Pkg.resolve()
    Pkg.develop("PandaModels")
    # add pandamodels dependencies: slow process
    Pkg.instantiate()            
    Pkg.build()
    Pkg.resolve()
    print("dev mode of PandaModels is added to julia packages")

    try:
        Pkg.activate("PandaModels")
        Main.using("PandaModels")
        print("using PandaModels in its dev mode!")
    except ImportError:
        # assert False
        raise ImportError("cannot use PandaModels in its dev mode")
      
    # activate julia base mode
    Pkg.activate()
    Pkg.free("PandaModels")
    Pkg.resolve()
コード例 #12
0
 def fit(self, X, y):
     """
     Fits the Local Discriminant Basis feature selection algorithm onto the
     input images X with labels y.
     """
     # restructure data
     n = len(X)
     Xt = np.stack(X, axis=2)
     Xt = Xt.reshape(-1, n)
     Xt = Xt.astype("float")
     # wrapper function for fit!
     Main.eval("""
         function fit(ldb, X, y)
             fit!(ldb, X, y)
         end
     """)
     # fit LDB
     Main.fit(self.ldb, Xt, y)
     # save attributes
     self.n = self.ldb.n
     self.Gamma = np.array(self.ldb.Γ)
     self.DM = np.array(self.ldb.DM)
     self.cost = np.array(self.ldb.cost)
     self.tree = np.array(self.ldb.tree)
     self.DP = np.array(self.ldb.DP)
     self.order = np.array(
         self.ldb.order) - 1  # python follows zero indexing
     return None
コード例 #13
0
ファイル: TreeRepy.py プロジェクト: rsonthal/TreeRep
def TreeRep_no_recursion(d):
    """
    This is a python wrapper to the TreeRep algorithm written in Julia.
    
    Input:
    d - Distance matrix, assumed to be symmetric with 0 on the diagonal
    Output:
    W - Adjacenct matrix of the tree. Note that W may have rows/cols full of zeros, and they should be ignored.
    Example Code:
    d = np.array([[0,2,3],[2,0,2],[3,2,0]])
    W = TreeRep(d)
    print(W)
    """
    Main.d = d
    Main.G, Main.dist = Main.eval(
        "TreeRep.metric_to_structure_no_recursion(d)")

    edges = Main.eval('collect(edges(G))')
    W = np.zeros_like(Main.dist)  # Initializing the adjacency matrix
    for edge in edges:
        src = edge.src - 1
        dst = edge.dst - 1
        W[src, dst] = Main.dist[src, dst]
        W[dst, src] = Main.dist[dst, src]

    return W
コード例 #14
0
def initialize_julia(): 
    sysimage_path = get_MORBIT_SYS_IMG()
    if sysimage_path:
        if os.path.isfile( MORBIT_SYS_IMG ):
            tprint(f"\tUsing sysimage at {MORBIT_SYS_IMG}")
        else:
            tprint(f"\tGoing to compile a sysimage at {MORBIT_SYS_IMG}")
            sysimage_path = make_sysimage()
    if not sysimage_path:
        tprint("\tNo sysimage specified.")
    
    tprint("MOP: Initializing Julia runtime. First time might take a bit.")
       
    init_api(sysimage_path)
    
    from julia import Main

    # include "hack" to make symbols available on the python side
    Main.include( os.path.join( os.path.dirname( __file__ ) , "pycall_sym.jl" ) )
    Main.include( os.path.join( os.path.dirname( __file__ ) , "prepare_path.jl" ) )
    
    prepare_morbit( Main )
    load_morbit( Main )
    
    tprint("Julia runtime all set up!")
    
    set_JULIA_MAIN(Main)
    return Main

                    
                
                
            
コード例 #15
0
ファイル: runpm.py プロジェクト: zzn1220/pandapower
def _call_powermodels(pm, julia_file):  #pragma: no cover
    buffer_file = os.path.join(tempfile.gettempdir(), "pp_pm.json")
    logger.debug("writing PowerModels data structure to %s" % buffer_file)
    with open(buffer_file, 'w') as outfile:
        json.dump(pm, outfile)
    try:
        import julia
        from julia import Main
    except ImportError:
        raise ImportError(
            "Please install pyjulia to run pandapower with PowerModels.jl")
    try:
        j = julia.Julia()
    except:
        raise UserWarning(
            "Could not connect to julia, please check that Julia is installed and pyjulia is correctly configured"
        )

    Main.include(os.path.join(pp_dir, "opf", 'pp_2_pm.jl'))
    try:
        run_powermodels = Main.include(julia_file)
    except ImportError:
        raise UserWarning("File %s could not be imported" % julia_file)
    result_pm = run_powermodels(buffer_file)
    return result_pm
コード例 #16
0
ファイル: main.py プロジェクト: nicholaskarlsen/FYS3150
def part_d():

    print "Running d"

    jcall.include("SIRS_MC_svar.jl")  # Import Julia program

    # Keep following parameters constant
    S0 = 300
    I0 = 100
    R0 = 0
    a0 = 4
    b = 1
    c = 0.5
    # But change the following
    percent_diff = [1, 1, .5, .5]  # maximum percent deviation from a0
    # Amplitude of deviation from a0
    Amp = [diff * a0 for diff in percent_diff]
    omega = [4, 0.25, 2, 0.25]  # Frequency of deviation from a0
    stop = [10, 70, 10, 70]  # Simulation time

    trials = 100  # No. times to run MC simulation

    for i in range(len(percent_diff)):
        plt.figure(figsize=[5, 2.5])

        # Get MC data from julia program (SIRS_MC.jl)
        command = "SIRS_svar(S0=%i, I0=%i, R0=%i, a0=%.2f, A=%.2f, omega=%.2f, b=%.2f, c=%.2f, stop_time=%i, trials=%i)"\
            % (S0, I0, R0, a0, Amp[i], omega[i], b, c, stop[i], trials)
        t, S, I, R = jcall.eval(command)

        for j in range(trials):
            plt.plot(t, S[j], color=S_colour, alpha=SIR_alpha)
            plt.plot(t, I[j], color=I_colour, alpha=SIR_alpha)
            plt.plot(t, R[j], color=R_colour, alpha=SIR_alpha)

        # Plot ODE solution on top
        inst = SIRS_ODE.SIRS(
            S0=S0, I0=I0, R0=R0, N=int(1e3), tN=stop[i], a=a0, b=b, c=c, Amplitude=Amp[i],
            omega=omega[i])
        inst.solve(inst.sirs_svar)
        t_ODE, S_ODE, I_ODE, R_ODE = inst.get()
        plt.plot(t_ODE, S_ODE, color="Black")
        plt.plot(t_ODE, I_ODE, color="Black")
        plt.plot(t_ODE, R_ODE, color="Black")
        # Mean MC on top of ODE
        plt.plot(t, np.mean(S, axis=0), linestyle="--", color=Mean_colour)
        plt.plot(t, np.mean(I, axis=0), linestyle="--", color=Mean_colour)
        plt.plot(t, np.mean(R, axis=0), linestyle="--", color=Mean_colour)

        plt.xlim(0, stop[i])
        plt.ylim(-10, 410)
        plt.title("A=%.2f, $\\omega$=%.2f" % (Amp[i], omega[i]))
        plt.xlabel("Time")
        plt.ylabel("No. People")
        plt.savefig("../figs/prob_d_fig_%i.pdf" % i)
        plt.savefig("../figs/prob_d_fig_%i.png" % i)
        plt.close()

    return
コード例 #17
0
    def get_protein(self, cell, props):
        #get_fcn = Main.eval('ProteinStoreMod.get')
        #return get_fcn(cell.proteins, props)
        Main.proteins = cell.proteins
        Main.props = props
        Main.eval('protein = ProteinStoreMod.get(proteins, props)')

        return Main.protein
コード例 #18
0
 def save_all_interaction_graphs(self, index, cell, path):
     Main.ea_step = index[0]
     Main.pop_index = index[1]
     Main.cell = cell
     Main.path = path
     Main.eval(
         'DataMod.save_all_graphs_for_cell(data, ea_step, pop_index, cell, path)'
     )
コード例 #19
0
ファイル: main.py プロジェクト: nicholaskarlsen/FYS3150
def part_e():

    print "Running e"

    jcall.include("SIRS_MC_vax.jl")  # Include Julia program

    # Keep following parameters constant
    S0 = 300
    I0 = 100
    R0 = 0
    a = 4
    b = 1
    c = 0.5
    # But change the following
    f = [50, 100, 200, 300]
    stop = [20, 20, 20, 20]  # Simulation time
    trials = 100  # No. times to run MC simulation

    for i in range(len(f)):
        plt.figure(figsize=[5, 2.5])

        command = "SIRS_vax(S0=%i, I0=%i, R0=%i, a=%.2f, b=%.2f, c=%.2f, f=%.2f, stop_time=%i, trials=%i)"\
            % (S0, I0, R0, a, b, c, f[i], stop[i], trials)

        t_MC, S_MC, I_MC, R_MC = jcall.eval(command)

        # Firt plot individual MC-cycles
        for j in range(trials):
            plt.plot(t_MC, S_MC[j], color=S_colour, alpha=SIR_alpha)
            plt.plot(t_MC, I_MC[j], color=I_colour, alpha=SIR_alpha)
            plt.plot(t_MC, R_MC[j], color=R_colour, alpha=SIR_alpha)

        # Plot ODE solution on top
        inst = SIRS_ODE.SIRS(
            S0=S0, I0=I0, R0=R0, N=int(1e5), tN=stop[i], a=a, b=b, c=c, f=f[i])
        inst.solve(inst.sirs_vax)
        t_ODE, S_ODE, I_ODE, R_ODE = inst.get()

        plt.plot(t_ODE, S_ODE, color=ODE_colour)
        plt.plot(t_ODE, I_ODE, color=ODE_colour)
        plt.plot(t_ODE, R_ODE, color=ODE_colour)
        # And finally MC mean on top of that.
        plt.plot(t_MC, np.mean(S_MC, axis=0),
                 linestyle="--", color=Mean_colour)
        plt.plot(t_MC, np.mean(I_MC, axis=0),
                 linestyle="--", color=Mean_colour)
        plt.plot(t_MC, np.mean(R_MC, axis=0),
                 linestyle="--", color=Mean_colour)

        plt.xlim(0, stop[i])
        plt.title("f=%.2f" % f[i])
        plt.xlabel("Time")
        plt.ylabel("No. People")
        plt.savefig("../figs/prob_e_fig_%i.pdf" % i)
        plt.savefig("../figs/prob_e_fig_%i.png" % i)
        plt.close()

    return
コード例 #20
0
 def save_all_gs_table_data(self, cell, index, filename):
     if cell is not None:
         Main.cell = cell
         Main.ea_step = index[0]
         Main.indiv_index = index[1]
         Main.filename = filename
         Main.eval(
             'DataMod.save_all_gs_table_data(data, cell, ea_step, indiv_index, filename)'
         )
コード例 #21
0
    def configure(self, params):
        super(JlPredictor, self).configure(params)
        logger.info(f"loading {JL_SCORE_PATH}")
        jl.eval(f'include("{JL_SCORE_PATH}")')
        logger.info(f"{JL_SCORE_PATH} loaded")
        from julia import Main

        Main.init(self._code_dir, self._target_type.value)
        self._model = Main.load_serialized_model(self._code_dir)
コード例 #22
0
    def get_neighbour_graph(self, index):
        Main.ea_step = index[0]
        Main.pop_index = index[1]
        Main.reg_step = index[2]
        Main.eval(
            'pixmap_data = DataMod.build_neighbour_comm_graph(data, ea_step, pop_index, reg_step)'
        )
        pixmap_data = Main.pixmap_data

        return pixmap_data
コード例 #23
0
def _read_source(module_name: str, source_file: str) -> None:
    """Read source if module not attached to julia Main yet.

    Parameters
    ----------
    module_name: Julia module name.^^
    source_file: Qualified Julia source file.
    """
    if not hasattr(Main, module_name):
        Main.include(source_file)
コード例 #24
0
def _call_pandamodels(buffer_file, julia_file, dev_mode):  # pragma: no cover

    try:
        import julia
        from julia import Main
        from julia import Pkg
        from julia import Base
    except ImportError:
        raise ImportError(
            "Please install pyjulia properly to run pandapower with PandaModels.jl."
        )

    try:
        julia.Julia()
    except:
        raise UserWarning(
            "Could not connect to julia, please check that Julia is installed and pyjulia is correctly configured"
        )

    if not Base.find_package("PandaModels"):
        logger.info(
            "PandaModels.jl is not installed in julia. It is added now!")
        Pkg.Registry.update()
        Pkg.add("PandaModels")

        if dev_mode:
            logger.info("installing dev mode is a slow process!")
            Pkg.resolve()
            Pkg.develop("PandaModels")
            # add pandamodels dependencies: slow process
            Pkg.instantiate()

        Pkg.build()
        Pkg.resolve()
        logger.info("Successfully added PandaModels")

    if dev_mode:
        Pkg.develop("PandaModels")
        Pkg.build()
        Pkg.resolve()
        Pkg.activate("PandaModels")

    try:
        Main.using("PandaModels")
    except ImportError:
        raise ImportError("cannot use PandaModels")

    Main.buffer_file = buffer_file
    result_pm = Main.eval(julia_file + "(buffer_file)")

    # if dev_mode:
    #     Pkg.activate()
    #     Pkg.free("PandaModels")
    #     Pkg.resolve()
    return result_pm
コード例 #25
0
ファイル: metric.py プロジェクト: rizalzaf/ap_perf_py
    def __init__(self, metric_str):
        self.metric_str = metric_str

        # check name and args
        name_args = metric_str.split("@metric")[1].strip().split(
            "\n")[0].split()
        self.name = name_args[0]
        self.args = name_args[1:]

        # run on julia
        Main.eval(metric_str)
コード例 #26
0
 def __init__(self,
              wt=Main.wavelet(Main.WT.haar),
              max_dec_level=Main.nothing,
              dm=Main.AsymmetricRelativeEntropy(),
              en=Main.TimeFrequency(),
              dp=Main.BasisDiscriminantMeasure(),
              top_k=Main.nothing,
              n_features=Main.nothing):
     """
     Initialize LDB object. 
     
     Arguments:
     - wt => Default is Main.wavelet(Main.WT.haar). Other acceptable wavelets
         are:
         * Main.wavelet(Main.WT.dbN)     [replace N with any number between 1:Inf]
         * Main.wavelet(Main.WT.coifN)   [replace N with any number from 2,4,6,8]
         * Main.wavelet(Main.WT.symN)    [replace N with any number between 4:10 inclusive]
         * Main.wavelet(Main.battN)      [replace N with any number from 2,4,6]
     - max_dec_level => Number of decomposition levels. Default of 
         Main.nothing means signal decomposes to max level.
     - dm => Discriminant measure. Default is 
         Main.AsymmetricRelativeEntropy(). Other acceptable values are:
         * Main.SymmetricRelativeEntropy()
         * Main.LpEntropy()
         * Main.HellingerDistance()
     - en => Energy map. Default is Main.TimeFrequency(). Other acceptable 
         value is:
         * Main.ProbabilityDensity()
     - dp => Discriminant power measure. Default is 
         Main.BasisDiscriminantMeasure(). Other acceptable values are:
         * Main.FishersClassSeparability()
         * Main.RobustFishersClassSeparability()
     - top_k => Number of coefficients used in each node to determine the 
         discriminant measure. Default of Main.nothing means all coefficients
         are used.
     - n_features => Number of features to be returned in output. Default of 
         Main.nothing means all features are returned.
     """
     self.wt = wt
     self.max_dec_level = max_dec_level
     self.dm = dm
     self.en = en
     self.dp = dp
     self.top_k = top_k
     self.n_features = n_features
     self.ldb = Main.LocalDiscriminantBasis(
         wt=self.wt,
         max_dec_level=self.max_dec_level,
         dm=self.dm,
         en=self.en,
         dp=self.dp,
         top_k=self.top_k,
         n_features=self.n_features)
コード例 #27
0
def JuliaModel(model):
    #
    if isinstance(model,HullWhiteModel):
        yc = JuliaYieldCurve(model.yieldCurve)
        return Main.HullWhiteModel(yc,model.meanReversion,model.volatilityTimes,model.volatilityValues)
    #
    if isinstance(model,QuasiGaussianModel):
        yc = JuliaYieldCurve(model.yieldCurve)
        return Main.QuasiGaussianModel(yc,model._d,
            model._times, model._sigma, model._slope, model._curve,
            model._delta, model._chi, model._Gamma)
    else:
        raise NotImplementedError('Implementation of JuliaModel for %s required.' % str(type(model)))
    return
コード例 #28
0
    def get_interaction_graph(self, index, cell):
        if cell is None:
            pixmap_data = []
        else:
            Main.cell = cell
            Main.ea_step = index[0]
            Main.pop_index = index[1]
            Main.reg_step = index[2]
            Main.eval(
                'pixmap_data = DataMod.build_graph_for_cell(data, ea_step, pop_index, reg_step, cell)'
            )
            pixmap_data = Main.pixmap_data

        return pixmap_data
コード例 #29
0
    def get_gs_table_data(self, cell, index):
        if cell is None:
            table_data = []
        else:
            Main.cell = cell
            Main.ea_step = index[0]
            Main.indiv_index = index[1]
            Main.reg_step = index[2]
            Main.eval(
                'table_data = DataMod.get_gs_table_data(data, cell, ea_step, indiv_index, reg_step)'
            )
            table_data = Main.table_data

        return table_data
コード例 #30
0
def minres(A, b, **kwargs):
    '''
    The function is a wrapper for the julia implementation of MINRES solver in IterativeSolver.jl package. \
    MINRES is a short-recurrence version of GMRES for solving :math:`Ax=b` approximately \
    for :math:`x` where :math:`A` is a symmetric, Hermitian, skew-symmetric or skew-Hermitian linear operator and :math:`b` the right-hand side vector.
        

    **Arguments**

        * A: linear operator.
        * b: right-hand side.

    **Keywords**

        * initially_zero::Bool = false: if true assumes that iszero(x) so that one matrix-vector product can be saved when computing the initial residual vector;
        * skew_hermitian::Bool = false: if true assumes that A is skew-symmetric or skew-Hermitian;
        * tol: tolerance for stopping condition :math:`|r_k| / |r_0| ≤ tol`. Note that the residual is computed only approximately;
        * maxiter::Int = size(A, 2): maximum number of iterations;
        * Pl: left preconditioner;
        * Pr: right preconditioner;
        * log::Bool = false: keep track of the residual norm in each iteration;
        * verbose::Bool = false: print convergence information during the iterations.

    **Output**

    **if log is false**

        * x: approximate solution.

    **if log is true**
        
        * x: approximate solution;
        * history: convergence history.
    '''
    return Main.minres(A, b, **kwargs)