Exemple #1
0
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()')
Exemple #2
0
    def run_julia(self):
        print("Loading Julia....")

        I = np.genfromtxt(self.us_exchanges_filename, delimiter=" ")
        age_fracs_with_name = np.genfromtxt(self.age_fracs_filename,
                                            delimiter=",")
        age_fracs = np.delete(age_fracs_with_name, 0, 1)

        employed = pd.read_csv(self.employment_filename,
                               dtype={
                                   "Sector": str,
                                   "Feb": np.int64
                               })

        j.eval("using DataFrames")
        julia_formatted_employed = j.DataFrame(employed.to_dict(orient='list'))

        print("Starting Julia run...")
        j.include("CASES.jl")
        returned_result = j.main(I, age_fracs, julia_formatted_employed)
        print("Julia run complete.")

        cases_2 = returned_result[1]
        pickle.dump(cases_2,
                    open(self.employment_filename + "_cases_2.bin", "wb"))

        cases_1 = returned_result[0]
        pickle.dump(cases_1,
                    open(self.employment_filename + "_cases_1.bin", "wb"))
        self.results.append(cases_1)
        self.results.append(cases_2)
Exemple #3
0
    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)
Exemple #4
0
	def import_diffeqpy(self):
		"""Import diffeqpy using lazy loading and creates an attribute so that loading happens only if required and loads in parallel.
		"""
		try:
			if self.der_solver_type == "diffeqpy":
				DERModelType = OpenDSSData.config['myconfig']['DERModelType']
				if six.PY3:
					tic = time.perf_counter()
				elif six.PY2:
					tic = time.clock()
				from diffeqpy import ode
				from julia import Sundials
				
				self.de = ode
				self.sundials = Sundials
				
				#from diffeqpy import de
				from julia import Main
				from julia import LinearAlgebra
				
				LinearAlgebra.BLAS.set_num_threads(18) #Set number of threads to be used by DiffEqPy if required
				OpenDSSData.log(level=20,msg="BLAS threads:{}".format(Main.eval("ccall((:openblas_get_num_threads64_, Base.libblas_name), Cint, ())"))) #Show number of threads being used by DiffEqPy
				if six.PY3:
					toc = time.perf_counter()
				elif six.PY2:
					toc = time.clock()
				OpenDSSData.log(level=10,msg="Time taken to import 'diffeqpy':{:.3f}".format(toc - tic))
		
		except:
			OpenDSSData.log()
    def inject_square_current(self, current):  #, section = None, debug=False):
        """Inputs: current : a dictionary with exactly three items, whose keys are: 'amplitude', 'delay', 'duration'
        Example: current = {'amplitude':float*pq.pA, 'delay':float*pq.ms, 'duration':float*pq.ms}}
        where \'pq\' is a physical unit representation, implemented by casting float values to the quanitities \'type\'.
        Description: A parameterized means of applying current injection into defined
        Currently only single section neuronal models are supported, the neurite section is understood to be simply the soma.

        """
        import numpy as np
        if 'injected_square_current' in current.keys():
            c = current['injected_square_current']
        else:
            c = current
        duration = float(c['duration'])  #.rescale('ms'))
        delay = float(c['delay'])  #.rescale('ms'))
        amp = float(c['amplitude'])  #.rescale('uA')
        tmax = 1.3  #00
        tmin = 0.0
        DT = 0.025
        T = np.linspace(tmin, tmax, int(tmax / DT))
        Iext_ = []
        for t in T:
            Iext_.append(Id(t, delay, duration, tmax, amp))
        self.attrs['N'] = len(Iext_)
        self.set_attrs(self.attrs)
        Main.eval('pA = 0.001nA')
        Main.eval("SNN.monitor(E2, [:v])")
        Main.dur = current["duration"]
        Main.current = current
        Main.delay = float(current["delay"])
        Main.temp_current = float(amp)
        Main.eval("E2.I = [deepcopy(temp_current)*pA]")
        #Main.eval("@show(E2.I)")
        Main.eval(
            'SNN.sim!([E2], []; dt =' + str(DT) +
            '*ms, delay=delay,stimulus_duration=1000,simulation_duration = 1300)'
        )
        #Main.eval('SNN.sim!([E2], []; dt = 0.015*ms, delay=current["delay"]*ms,stimulus_duration=1000*ms,simulation_duration = 1300*ms)')

        Main.eval("v = SNN.getrecord(E2, :v)")
        v = Main.v
        #Main.eval('SNN.vecplot(E2, :v) |> display')
        self.vM = AnalogSignal(v, units=pq.mV, sampling_period=DT * pq.ms)
        return self.vM
Exemple #6
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
Exemple #7
0
    def set_attrs(self, attrs):
        JUIZI = {
            'a': 0.02,
            'b': 0.2,
            'c': -65,
            'd': 8,
        }
        if not len(attrs):
            attrs = JUIZI

        Main.attrs = attrs
        Main.eval('param = SNN.IZParameter(;a =  attrs["a"], b = attrs["b"], c = attrs["c"], d = attrs["d"])')
        self.attrs.update(attrs)
        #Main.N_ = attrs["N"]
        Main.eval('E2 = SNN.IZ(;N = 1, param = param)')
        Main.eval("N = Int32(1)")
Exemple #8
0
def jl(src, locals=None, globals=None):
    """ 
    Execute some Julia code and return the answer. The Julia code is executed in
    the top-level of Julia's Main module.
    
    You can interpolate Python values into the Julia expression in the same way
    as with `%julia` magic for IPython, and scoping behaves the same way as well.
    
    See: https://pyjulia.readthedocs.io/en/latest/usage.html#ipython-magic
    """

    if locals is None: locals = get_caller_locals()
    if globals is None: globals = get_caller_globals()

    src = unicode(src)
    return_value = "nothing" if src.strip().endswith(";") else ""

    return Main.eval("""
        _PyJuliaHelper.@prepare_for_pyjulia_call begin
            begin %s end
            %s
        end
        """ % (src, return_value))(globals, locals)