def init_julia(self): print("Waiting for Julia to compile...") j = Julia() j.include( os.path.join(os.path.dirname(__file__), 'n-dof', 'dynamics.jl')) j.using("Dynamics") return j
def solve_it(input_data): """ Run appropriate jl script to generate an integer. """ jl = Julia() jl.include("any_integer.jl") result = jl.eval(f'generate_any_integer("{input_data}")') return result
def solve_it(input_data): """ Run appropriate jl script to solve the knapsack problem in Julia. """ jl = Julia() jl.include("knapsack.jl") output_data = jl.eval(f'optimise_knapsack("{input_data}", timeout=60)') return output_data
def makeFractal(self, gradients, file='spiral0.frac'): frac_data = FractalData().get_one_frac(file) # self.verify_data(frac_data) if frac_data['type'] == 'mandelbrot': return Mandelbrot(frac_data, gradients) elif frac_data['type'] == 'julia': return Julia(frac_data, gradients) elif frac_data['type'] == 'burningship': return Burningship(frac_data, gradients) elif frac_data['type'] == 'phoenix': return Phoenix(frac_data, gradients)
def setup(): jul = Julia() include(jul, 'setup.jl') # Make Julia functions and types exported from # DifferentialEquations accessible: jul.add_module_functions('DifferentialEquations') # pysolve has to be treated manually: # See: https://github.com/JuliaPy/pyjulia/issues/117#issuecomment-323498621 jul.pysolve = jul.eval('pysolve') return jul
def __init__(self, shell): """ Parameters ---------- shell : IPython shell """ super(JuliaMagics, self).__init__(shell) print("Initializing Julia interpreter. This may take some time...", end='') # Flush, otherwise the Julia startup will keep stdout buffered sys.stdout.flush() self.julia = Julia(init_julia=True) print()
def ipython_options(**kwargs): from traitlets.config import Config from julia import Julia julia = Julia(**kwargs) Main = JuliaNameSpace(julia) user_ns = dict( julia=julia, Main=Main, ) c = Config() c.TerminalIPythonApp.display_banner = False c.TerminalInteractiveShell.confirm_exit = False return dict(user_ns=user_ns, config=c)
def main(): from julia import Julia julia = Julia() julia.eval("@eval Main import Base.MainInclude: include") from julia import Main Main.include("test.jl") arr = np.array([1, 2, 3]) ret = Main.twice_array(arr) print("arr=", arr) print("ret=", ret) jlsin = Main.sin Main.rad45degree = np.pi / 4 print(jlsin(Main.rad45degree), np.sqrt(2) / 2)
def init_api(sysimage_path): jlinfo = JuliaInfo.load(julia = get_JULIA_RUNTIME_NAME()) if not jlinfo.libpython_path: logging.info("PyCall does not seem to be installed. Trying to remedy this fact...") install( julia = get_JULIA_RUNTIME_NAME() ) elif get_FORCE_PYCALL_REBUILD or not os.path.isfile(jlinfo.python) or not os.path.samefile( jlinfo.python, executable ): logging.info("PyCall not compatbile, rebuilding...") build_pycall( julia = get_JULIA_RUNTIME_NAME(), quiet = True ) try: Julia( runtime = get_JULIA_RUNTIME(), compiled_modules = False, sysimage = sysimage_path) except JuliaError as e: logging.warn("Could not load Julia.") raise e
def maybe_load_pyjulia(): """ Execute ``julia.Julia(init_julia=False)`` if appropriate. It is useful since it skips initialization when creating the global "cached" API. This makes PyJuli initialization slightly faster and also makes sure to not load incompatible `libjulia` when the name of the julia command of this process is not `julia`. """ if (os.environ.get("IPYTHON_JL_SETUP_PYJULIA", "yes").lower() in ("yes", "t", "true")): try: from julia import Julia except ImportError: pass else: with init_julia_message_on_failure(): Julia(init_julia=False)
def generate_preds(X, treatment, algorithm, matched, result_path, SEED = 1, prediction = 'DEATH'): ## Results path and file names match_status = 'matched' if matched else 'unmatched' result_path = result_path + str(algorithm) +'/' file_list = os.listdir(result_path) file_start = str(treatment) + '_' + match_status + '_' + prediction.lower() + '_seed' + str(SEED) file_name = '' for f in file_list: if f.startswith(file_start) & ~f.endswith('.json'): file_name = result_path+f if file_name == '': print("Invalid treatment/algorithm combination (" + str(treatment) + ", " + str(algorithm)+ ")") prob_pos = np.empty(X.shape[0]) prob_pos[:] = np.nan return prob_pos else: with open(file_name, 'rb') as file: model_file = pickle.load(file) ## Match data to dummy variables for this dataframe train = model_file['train'].drop(prediction, axis=1) train_y = model_file['train'][prediction] X = X.reindex(labels = train.columns, axis = 1).replace(np.nan,0) if algorithm == 'oct': from julia import Julia jl = Julia(sysimage='/home/hwiberg/software/julia-1.2.0/lib/julia/sys_iai.so') from interpretableai import iai model = iai.read_json(file_name+'.json') prob_pos = model.predict_proba(X).iloc[:,1] # elif algorithm == 'xgboost': else: model = model_file['model'] prob_pos = model.predict_proba(X)[:, 1] return prob_pos
import os, copy, sys, json os.environ[ "PATH"] += os.pathsep + '/anaconda3/pkgs/graphviz-2.40.1-h69955ae_1/bin/' sys.path.append(os.getcwd().split("src")[0]) from src.helpers import useful_paths, size_data, useful_name, local_path from julia import Julia if "JULIE" in local_path.NAME_MACHINE: Julia(runtime= "/Applications/Julia-1.3.app/Contents/Resources/julia/bin/julia", compiled_modules=False) elif "CAMBRIDGE" in local_path.NAME_MACHINE: julia_path = os.path.join('C:', os.sep, 'Users', 'jpoullet', 'AppData', 'Local', 'Julia-1.2.0', 'bin', 'julia.exe') Julia(runtime=julia_path, compiled_modules=False) else: assert "LAGOS" in local_path.NAME_MACHINE, local_path.NAME_MACHINE julia_path = os.path.join('C:', os.sep, 'Users', 'jpoullet', 'AppData', 'Local', 'Julia-1.3.1', 'bin', 'julia.exe') Julia(runtime=julia_path, compiled_modules=False) from interpretableai import iai import pandas as pd import numpy as np from src.learning_step.learning_trees import constraint from src.optimization_step.direct_MIP import clustering_cst_parallel_MIP from src.data_set_creation.stops.manager import stops_manager_cvrptw from src.learning_step.pixelation import pixelManagerAbsolut
# coding: utf-8 # In[2]: import numpy as np from ase.calculators.calculator import Calculator import os from julia import Julia if not os.environ.has_key('JL_RUNTIME_PATH'): julia = Julia() else: # "/Users/ortner/gits/julia6bp/usr/bin/julia" julia = Julia(jl_runtime_path=os.environ['JL_RUNTIME_PATH']) julia.using("NBodyIPs") def import_IP(potname): #julia.eval("IP = load_ip(\"" + potname + "\")") julia.eval("IP = load_ip(\"" + potname + "\")") julia.eval("IPf = fast(IP)") IP = julia.eval("IPf") return IP
print(*build) subprocess.check_call(build, env=env) else: yield # Initialize Julia as early as possible. I don't fully understand it, # but initializing julia.Julia (loading libjulia) before some other # Python packages (depending on C extension?) helps avoiding OSError # complaining GLIBCXX version. # https://github.com/JuliaDiffEq/diffeqpy/pull/14/commits/5479173b29da4034d6a13c02739e7ac4d35ef96a # # It would be cleaner to use `pytest_addoption` but I couldn't find a # "pre-collection hook" where I can safely initialize Julia before # loading modules. Although it is a bit ugly, it is simple if it is # executed at the top level. TEST_PYJULIA = os.environ.get('TEST_PYJULIA', 'no') == 'yes' if TEST_PYJULIA: with maybe_rebuild(): from julia import Julia JL = Julia() @pytest.fixture def julia(): """ pytest fixture for providing a `julia.Julia` instance. """ if TEST_PYJULIA: return JL else: pytest.skip("TEST_PYJULIA=no")
from fractal import Fractal from julia import Julia from mandelbrot import Mandelbrot from newton import Newton from pheonix import Pheonix # Static constant fractal instances. MANDELBROT = Mandelbrot("Mandelbrot Set") NEWTON = Newton("Newton Fractal") JULIA = Julia("Julia Set") PHEONIX = Pheonix("Pheonix Fractal") def getFractal(fractal_id): return Fractal.FRACTALS[fractal_id] def getFractals(): return Fractal.FRACTALS
import pygame from julia import Julia from display import Screen from threading import Thread screen_width = 500 screen_height = 500 screen_running = True show_axis = True p_i, q_i = -0.904, 0.224 display = Screen(screen_width, screen_height) julia = Julia(screen_width, screen_height, [ display.bg_color, display.RED, display.WHITE, display.YELLOW, display.GREEN, display.BLUE ], p_i, q_i) display.julia = julia display.running = screen_running MAIN_THREAD = Thread(target=display.run) MAIN_THREAD.setDaemon(True) MAIN_THREAD.start() def update(): display.draw_background(show_axis) julia.calculate() display.show_layer(julia.image) def p(p):
def plot_julia() -> None: """Plot the Julia set.""" print('Please wait, a Julia set is being loaded.') julia = Julia(constant=complex(-0.1, 0.8), iteration_limit=24, accuracy=500, real_domain=(-2.0, 2.0), imaginary_domain=(-2.0, 2.0)) julia.plot()
def test_solve(self): cur_obj = Julia(100, 100, -1, 1, -1, 1) cur_obj.solve() assert (len(cur_obj.img) == 30000) assert (cur_obj.img[0] == 255) assert (cur_obj.img[242] == 255)
# first load the correct Julia Binary. # (on my system pyjulia never finds it by itself for some reason...) from julia import Julia jl = Julia(runtime="/Users/ortner/gits/julia11/julia") # import `Main` since this is where Julia loads all new modules from julia import Main # load anything else you need from ase.build import bulk # this generates a new descriptor; make sure to store this in `Main` (i.e. # inside of Julia) - see help text to see the complete set of options Main.eval("using ACE") Main.eval("desc = ACE.Descriptors.SHIPDescriptor(:Si, deg=6, rcut=4.0)") # create an ase.Atoms object by whatever means Main.at = bulk("Si", cubic=True) * (2, 2, 2) # compute the corresponding descriptors ... D = Main.eval("ACE.Descriptors.descriptors(desc, at)") Nx = Main.length(Main.desc) Nat = Main.at.positions.shape[0] print("Nx = ", Nx, "; Nat = ", Nat, "; D.shape = ", D.shape)
def test_get_file_name(self): cur_obj = Julia(100, 100, -1, 1, -1, 1) fn = cur_obj.get_file_name() fn2 = cur_obj.get_file_name() assert (fn != fn2)
import evaluation.treatment_utils as u import evaluation.descriptive_utils as d import pandas as pd import numpy as np import itertools from scipy import stats import matplotlib.pyplot as plt from julia import Julia jl = Julia(sysimage='/home/hwiberg/software/julia-1.2.0/lib/julia/sys_iai.so') from interpretableai import iai #%% Version-specific parameters # version = 'matched_single_treatments_hope_bwh/' # train_file = '_hope_matched_all_treatments_train.csv' # data_list = ['train','test','validation_all','validation_partners'] version = 'matched_single_treatments_hypertension/' train_file = '_hope_hm_cremona_matched_all_treatments_train.csv' data_list = [ 'train', 'test', 'validation_all', 'validation_partners', 'validation_hope', 'validation_hope_italy' ] #%% General parameters data_path = '../../covid19_treatments_data/' + version preload = True matched = True
import array import math import unittest from julia import Julia, JuliaError import sys import os python_version = sys.version_info julia = Julia(jl_runtime_path=os.getenv("JULIA_EXE"), debug=True) class JuliaTest(unittest.TestCase): def test_call(self): julia._call('1 + 1') julia._call('sqrt(2.0)') def test_eval(self): self.assertEqual(2, julia.eval('1 + 1')) self.assertEqual(math.sqrt(2.0), julia.eval('sqrt(2.0)')) self.assertEqual(1, julia.eval('PyObject(1)')) self.assertEqual(1000, julia.eval('PyObject(1000)')) self.assertEqual((1, 2, 3), julia.eval('PyObject((1, 2, 3))')) def test_call_error(self): try: julia._call('undefined_function_name()') self.fail('No error?') except JuliaError:
import numpy as np import scipy as sp from scipy.stats import rankdata from functools import partial from sklearn.metrics import pairwise_distances import os import sys from sklearn.base import BaseEstimator, TransformerMixin from julia import Julia jl = Julia(compiled_modules=False) class SURF(BaseEstimator, TransformerMixin): """sklearn compatible implementation of the SURF algorithm Casey S Greene, Nadia M Penrod, Jeff Kiralis, Jason H Moore. Spatially Uniform ReliefF (SURF) for computationally-efficient filtering of gene-gene interactions Author: Jernej Vivod """ def __init__(self, n_features_to_select=10, dist_func=lambda x1, x2: np.sum(np.abs(x1 - x2)), learned_metric_func=None): self.n_features_to_select = n_features_to_select # number of features to select self.dist_func = dist_func # metric function self.learned_metric_func = learned_metric_func # learned metric function # Use function written in Julia programming language to update feature weights. script_path = os.path.abspath(__file__)
def setup(): jul = Julia() jul.using("DiffEqPy") return jul
from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.metrics import classification_report, confusion_matrix import itertools import time from threading import Thread run_OCT = False if run_OCT == True: from julia import Julia Julia(runtime= '/Applications/Julia-0.7.app/Contents/Resources/julia/bin/julia', compiled_modules=False) from interpretableai import iai from julia import Distributed Distributed.addprocs(5) models1 = { "RFC": RandomForestClassifier, "XGB": GradientBoostingClassifier, "Log": LogisticRegression, "CART": tree.DecisionTreeClassifier, "OCT": iai.OptimalTreeClassifier } models2 = { "RFC": RandomForestRegressor, "XGB": GradientBoostingRegressor,
import sys from datetime import datetime from julia import Julia jl = Julia('/home/ianc/src/julia-1.3.1/bin/julia', compiled_modules=False) from julia import Main S = """ include("main.jl") main(fasta_files=["../../chloe/xxx.fa"]) """ def run(): s = datetime.now() Main.eval(S) e = datetime.now() print(e - s, file=sys.stderr) run() run() run()
def __init__(self, julia=None): from julia import Julia self.julia = Julia() if julia is None else julia self.magic_re = re.compile(r".*(\s|^)%%?julia\s*")
def test_init(self): cur_obj = Julia(100, 100, -1, 1, -1, 1) assert (cur_obj.max_iter == 100) assert (cur_obj.x_min == -1)
from julia import JuLIP from julia.JuLIP import energy from julia.JuLIP import forces from julia.JuLIP import stress ASEAtoms = Main.eval("ASEAtoms(a) = ASE.ASEAtoms(a)") ASECalculator = Main.eval("ASECalculator(c) = ASE.ASECalculator(c)") fixedcell = Main.eval("fixedcell(a) = JuLIP.Constraints.FixedCell(a)") variablecell = Main.eval("variablecell(a) = JuLIP.Constraints.VariableCell(a)") convert = Main.eval("julip_at(a) = JuLIP.Atoms(a)") from julia import Julia julia = Julia() julia.using("JuLIP") def pot(potname, fast=False): try: julia.eval("IP = " + potname) ASE_IP = JulipCalculator("IP") return ASE_IP except: print("couldn't find potential") def NBodyIPs(potname, fast=False): try: julia.using("NBodyIPs")
def make_bridge(): # pragma: no cover with timer(logger.info, "Creating Julia bridge"): return Julia()