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
Exemple #2
0
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
Exemple #3
0
    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()
Exemple #4
0
 def setup(self):
     "initialize the UI, set up all view objects"
     pygame.display.init()
     pygame.font.init()
     if "fullscreen" in config["interface"] and \
       config["interface"]["fullscreen"]:
         res = pygame.display.list_modes()[0]
         if config["interface"]["resolution"] is not None and \
           len(config["interface"]["resolution"]) == 2:
             res = config["interface"]["resolution"]
         args = (res, pygame.FULLSCREEN|pygame.HWSURFACE)
     elif "resolution" in config["interface"] and \
       len(config["interface"]["resolution"]) == 2:
         args = (config["interface"]["resolution"], pygame.HWSURFACE)
     else:
         raise ValueError("Interface: config must either " + \
             "define a resolution or set the fullscreen option")
     self.surf = pygame.display.set_mode(*args)
     font = None
     if "font" in config["interface"]:
         font = pygame.font.match_font(config["interface"]["font"])
     if font is None:
         font = pygame.font.get_default_font()
     self.font = pygame.font.Font(font, 14)
     self.mandel = Julia(Julia.MANDEL, self.surf.get_size(), self.surf,
       config["interface"]["colors"][0], config["julia"]["factor"],
       (-2 / 3, 0), config["julia"]["max_iter"],
       config["coloring"], True, (.0, .0),
       max_nodes=config["julia"]["max_nodes"])
     self.julia = Julia(Julia.JULIA, self.surf.get_size(), self.surf,
       config["interface"]["colors"][0], config["julia"]["factor"],
       (.0, .0), config["julia"]["max_iter"], config["coloring"],
       max_nodes=config["julia"]["max_nodes"])
     self.smallju = Julia(Julia.JULIA, config["smallju"]["size"],
       self.surf, config["interface"]["colors"][0],
       config["smallju"]["factor"], (.0, .0),
       config["smallju"]["max_iter"], config["coloring"],
       max_nodes=config["julia"]["max_nodes"])
     self.lang = "en" if len(sys.argv) == 1 or \
         sys.argv[-1] not in config["interface"]["text"] else \
         sys.argv[-1]
     fn = "README.txt"
     if self.lang != "en":
         fn = "README.{}.txt".format(self.lang)
     self.text = Text(self.surf, self.font, fn, (
         config["interface"]["colors"][2],
         config["interface"]["colors"][0],
     ))
Exemple #5
0
 def _give_image(self, julia: Julia) -> plt.imshow:
     """Find a matplotlib image corresponding to a given Julia set."""
     last_convergent_array = np.array(julia.last_convergent_array())
     plt.xlabel("Real part")
     plt.ylabel("Imaginary part")
     return plt.imshow(last_convergent_array.T, cmap='RdGy', interpolation='bilinear',
                       extent=self.real_domain + self.imaginary_domain, animated=True)
Exemple #6
0
class JuliaMagics(Magics):
    """A set of magics useful for interactive work with Julia.
    """
    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()

    @line_cell_magic
    def julia(self, line, cell=None):
        """
        Execute code in Julia, and pull some of the results back into the
        Python namespace.
        """
        src = str(line if cell is None else cell)
        return self.julia.run(src)
Exemple #7
0
class JuliaMagics(Magics):
    """A set of magics useful for interactive work with Julia.
    """
    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()
        
    @line_cell_magic
    def julia(self, line, cell=None):
        """
        Execute code in Julia, and pull some of the results back into the
        Python namespace.
        """
        src = str(line if cell is None else cell)
        return self.julia.run(src)
Exemple #8
0
class JuliaMagics(Magics):
    """A set of magics useful for interactive work with Julia.
    """
    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()

    @line_cell_magic
    def julia(self, line, cell=None):
        """
        Execute code in Julia, and pull some of the results back into the
        Python namespace.
        """
        src = compat.unicode_type(line if cell is None else cell)

        try:
            ans = self.julia.eval(src)
        except JuliaError as e:
            print(e.message, file=sys.stderr)
            ans = None

        return ans
Exemple #9
0
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)
Exemple #10
0
class JuliaMagics(Magics):
    """A set of magics useful for interactive work with Julia.
    """
    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()

    @line_cell_magic
    def julia(self, line, cell=None):
        """
        Execute code in Julia, and pull some of the results back into the
        Python namespace.
        """
        src = compat.unicode_type(line if cell is None else cell)

        try:
            ans = self.julia.eval(src)
        except JuliaError as e:
            print(e.message, file=sys.stderr)
            ans = None

        return ans
 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)
Exemple #12
0
 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
Exemple #13
0
    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()
Exemple #14
0
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
Exemple #15
0
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 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)
Exemple #17
0
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
Exemple #18
0
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
Exemple #19
0
class JuliaCompleter(Singleton):

    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*")
        # With this regexp, "=%julia Cha<tab>" won't work.  But maybe
        # it's better to be conservative here.

    @cached_property
    def jlcomplete(self):
        return self.julia.eval("""
        import REPL
        (str, pos) -> begin
            ret, ran, should_complete = REPL.completions(str, pos)
            return (
                map(REPL.completion_text, ret),
                (first(ran), last(ran)),
                should_complete,
            )
        end
        """)

    def julia_completions(self, full_text: str, offset: int):
        self.last_text = full_text
        match = self.magic_re.match(full_text)
        if not match:
            return []
        prefix_len = match.end()
        jl_pos = offset - prefix_len
        jl_code = full_text[prefix_len:]
        texts, (jl_start, jl_end), should_complete = \
            self.jlcomplete(jl_code, jl_pos)
        start = jl_start - 1 + prefix_len
        end = jl_end + prefix_len
        completions = [Completion(start, end, txt) for txt in texts]
        self.last_completions = completions
        # if not should_complete:
        #     return []
        return completions
Exemple #20
0
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
Exemple #21
0
class Interface:
    """
    Main interface class.

    Provides a pygame UI for a mandelbrot set.
    Features:
    · julia preview
    · full-window julia set
    · the README in rendered form, scroll with arrow keys
    · decorator-based automagic event handler
    · a basic "load balancer" to only run one update per main loop iteration
    """
    def __init__(self):
        self.running = True
        self.update = False
        self.surf = None
        self.font = None
        self.smallju_show = False
        self.smallju = None
        self.move_focus = True
        self.mandel = None
        self.view_proxy = "mandel"
        self.view_proxy_old = "mandel"
        self.julia = None
        self.text = None
        self.keyhelps = {}
        self.grid = False
        self.setup()

    def setup(self):
        "initialize the UI, set up all view objects"
        pygame.display.init()
        pygame.font.init()
        if "fullscreen" in config["interface"] and \
          config["interface"]["fullscreen"]:
            res = pygame.display.list_modes()[0]
            if config["interface"]["resolution"] is not None and \
              len(config["interface"]["resolution"]) == 2:
                res = config["interface"]["resolution"]
            args = (res, pygame.FULLSCREEN|pygame.HWSURFACE)
        elif "resolution" in config["interface"] and \
          len(config["interface"]["resolution"]) == 2:
            args = (config["interface"]["resolution"], pygame.HWSURFACE)
        else:
            raise ValueError("Interface: config must either " + \
                "define a resolution or set the fullscreen option")
        self.surf = pygame.display.set_mode(*args)
        font = None
        if "font" in config["interface"]:
            font = pygame.font.match_font(config["interface"]["font"])
        if font is None:
            font = pygame.font.get_default_font()
        self.font = pygame.font.Font(font, 14)
        self.mandel = Julia(Julia.MANDEL, self.surf.get_size(), self.surf,
          config["interface"]["colors"][0], config["julia"]["factor"],
          (-2 / 3, 0), config["julia"]["max_iter"],
          config["coloring"], True, (.0, .0),
          max_nodes=config["julia"]["max_nodes"])
        self.julia = Julia(Julia.JULIA, self.surf.get_size(), self.surf,
          config["interface"]["colors"][0], config["julia"]["factor"],
          (.0, .0), config["julia"]["max_iter"], config["coloring"],
          max_nodes=config["julia"]["max_nodes"])
        self.smallju = Julia(Julia.JULIA, config["smallju"]["size"],
          self.surf, config["interface"]["colors"][0],
          config["smallju"]["factor"], (.0, .0),
          config["smallju"]["max_iter"], config["coloring"],
          max_nodes=config["julia"]["max_nodes"])
        self.lang = "en" if len(sys.argv) == 1 or \
            sys.argv[-1] not in config["interface"]["text"] else \
            sys.argv[-1]
        fn = "README.txt"
        if self.lang != "en":
            fn = "README.{}.txt".format(self.lang)
        self.text = Text(self.surf, self.font, fn, (
            config["interface"]["colors"][2],
            config["interface"]["colors"][0],
        ))

    def view(self):
        "return the current view according to view_proxy"
        return getattr(self, self.view_proxy)

    def render_keyhelp(self):
        "render text field for the top right keyhelp description"
        l = config["interface"]["text"][self.lang]
        td = config["interface"]["text_display"]
        txt = [l[x] for x in td[self.view_proxy]]
        if self.view_proxy == "mandel" and self.mandel.start != (.0, .0):
            txt.extend([l[x] for x in td["mandel_startpos"]])
        if None in config["interface"]["text_display"]:
            txt.extend([l[x] for x in td[None]])
        txt = tuple(txt)
        if txt in self.keyhelps:
            return self.keyhelps[txt]
        txs = [font_render(self.font, x) for x in txt]
        fs = pygame.Surface(
            (max(x.get_width() for x in txs), sum(x.get_height() for x in txs)),
            pygame.HWSURFACE, self.surf)
        h = 0
        for x in txs:
            fs.blit(x, (0, h))
            h += x.get_height()
        self.keyhelps[txt] = fs
        return fs

    def draw(self):
        """
        draw frame
        · blit view frames
        · draw top text: description of keys
        · draw path according to focus
        · draw bottom text: focus coordinates
        """
        sz = self.surf.get_size()
        self.surf.blit(self.view().surf, self.view().blitpos)
        if self.view_proxy == "mandel" and self.smallju_show:
            self.surf.blit(self.smallju.surf, self.smallju.blitpos)
        if self.grid:
            vp = [self.view().realpos(x) for x in ((0, 0), sz)]
            c = config["interface"]["grid_size"]
            for x in range(int(vp[0][0] / c), int(vp[1][0] / c) + 1):
                x *= c
                pygame.draw.line(self.surf, config["interface"]["colors"][3],
                  self.view().pxpos((x, vp[0][1])),
                  self.view().pxpos((x, vp[1][1])))
            for y in range(int(vp[0][1] / c), int(vp[1][1] / c) + 1):
                y *= c
                pygame.draw.line(self.surf, config["interface"]["colors"][3],
                  self.view().pxpos((vp[0][0], y)),
                  self.view().pxpos((vp[1][0], y)))
        fs = self.render_keyhelp()
        self.surf.blit(fs, (sz[0] - fs.get_width(), 0))
        if "draw_path" in dir(self.view()):
            fc = self.view().draw_path(self.surf,
              config["interface"]["colors"][1])
            if fc is not None:
                fs = font_render(self.font,
                  config["interface"]["text"][self.lang]["float"].format(
                   fc[0][0], fc[0][1], fc[1][0], fc[1][1]))
                r = fs.get_rect()
                r.move_ip((sz[0] - r.width, sz[1] - r.height))
                self.surf.blit(fs, r.topleft)
        pygame.display.update()

    @handler(type=pygame.QUIT)
    @handler(type=pygame.KEYDOWN, key=pygame.K_q)
    @handler(type=pygame.KEYDOWN, key=pygame.K_ESCAPE)
    def quit(self, ev):
        self.running = False

    @handler(state="mandel", type=pygame.MOUSEBUTTONDOWN)
    @handler(state="julia", type=pygame.MOUSEBUTTONDOWN)
    def mbdown(self, ev):
        "left click: pin focus coord, right click: unpin focus coord"
        if ev.button == 1:
            self.view().focus = ev.pos
            self.move_focus = False
            if self.view_proxy == "mandel":
                self.julia.set_start(self.mandel.realpos(ev.pos))
                self.smallju.set_start(self.mandel.realpos(ev.pos))
        elif ev.button == 3:
            self.view().focus = None
            self.move_focus = True
        self.update = True

    @handler(state="mandel", type=pygame.MOUSEMOTION)
    @handler(state="julia", type=pygame.MOUSEMOTION)
    def mmove(self, ev):
        "move focus when focus coord is unpinned"
        if not self.move_focus or self.view().updating:
            return
        self.view().focus = ev.pos
        if self.view_proxy == "mandel":
            self.smallju.set_start(self.view().realpos(ev.pos))
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_m)
    def mandel_start(self, ev):
        if self.mandel.focus is None:
            return
        self.mandel.set_start(self.mandel.realpos(self.mandel.focus))
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_r)
    def mandel_restore(self, ev):
        self.mandel.set_start((.0, .0))
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_j)
    @handler(state="julia", type=pygame.KEYDOWN, key=pygame.K_j)
    def julia_toggle(self, ev):
        if self.view_proxy == "mandel" and self.julia.start is not None:
            self.view_proxy = "julia"
        elif self.view_proxy == "julia":
            self.view_proxy = "mandel"
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_p)
    def smallju_toggle(self, ev):
        self.smallju_show ^= True
        self.smallju.set_start(self.mandel.realpos(self.mandel.focus))
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_i)
    @handler(state="julia", type=pygame.KEYDOWN, key=pygame.K_i)
    @handler(state="text", type=pygame.KEYDOWN, key=pygame.K_i)
    def text_toggle(self, ev):
        if self.view_proxy != "text":
            self.view_proxy_old = self.view_proxy
            self.view_proxy = "text"
        else:
            self.view_proxy = self.view_proxy_old
        self.text.keyup(ev)
        self.update = True

    @handler(state="text", type=pygame.KEYDOWN, key=pygame.K_UP)
    @handler(state="text", type=pygame.KEYDOWN, key=pygame.K_DOWN)
    @handler(state="text", type=pygame.KEYUP, key=pygame.K_UP)
    @handler(state="text", type=pygame.KEYUP, key=pygame.K_DOWN)
    def text_proxy(self, ev):
        "route events to Text object"
        getattr(self.text, "keyup" if ev.type == pygame.KEYUP else "scroll_down"
            if ev.key == pygame.K_DOWN else "scroll_up")(ev)
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_g)
    @handler(state="julia", type=pygame.KEYDOWN, key=pygame.K_g)
    def grid_toggle(self, ev):
        self.grid ^= 1
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_b)
    @handler(state="julia", type=pygame.KEYDOWN, key=pygame.K_b)
    def budda_toggle(self, ev):
        self.view().toggle_buddha_mode()
        self.update = True

    @handler(state="mandel", type=pygame.KEYDOWN, key=pygame.K_c)
    @handler(state="julia", type=pygame.KEYDOWN, key=pygame.K_c)
    def budda_toggle(self, ev):
        self.view().toggle_inverse_buddha_mode()
        self.update = True

    def run(self):
        """
        main loop
        · run events
        · run .update() functions
        · update viewport
        · and sleep if there's time left
        """
        smallju_frame = False
        while self.running:
            t = time.clock_gettime(time.CLOCK_MONOTONIC)
            for ev in pygame.event.get():
                ev.state = self.view_proxy
                handler.dispatch(ev, self, ev)
            if self.view_proxy == "mandel" and self.smallju_show and \
              self.smallju.updating and smallju_frame:
                self.smallju.update()
                self.update = True
            elif self.view().updating:
                self.view().update()
                self.update = True
            smallju_frame ^= self.smallju_show
            if self.update:
                self.draw()
                self.update = False
            # naively sleep until we expect the new frame
            t = time.clock_gettime(time.CLOCK_MONOTONIC) - t
            if t < config["interface"]["max_fps"]:
                time.sleep(config["interface"]["max_fps"] - t)
            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")
Exemple #23
0
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:
Exemple #24
0
# 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)
Exemple #25
0
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__)
Exemple #26
0
def make_bridge():  # pragma: no cover
    with timer(logger.info, "Creating Julia bridge"):
        return Julia()
Exemple #27
0
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
import numpy as np
from scipy.stats import rankdata
from functools import partial
from sklearn.base import BaseEstimator, TransformerMixin
import numba as nb
import os
from julia import Julia
jl = Julia(compiled_modules=False)


class Relief(BaseEstimator, TransformerMixin):
    """sklearn compatible implementation of the Relief algorithm

    Kenji Kira, Larry A. Rendell.
    The Feature Selection Problem: Traditional Methods and a New Algorithm.
    
    Author: Jernej Vivod

    """

    # Constructor: initialize learner.
    def __init__(self,
                 n_features_to_select=10,
                 m=-1,
                 dist_func=lambda x1, x2: np.sum(np.abs(x1 - x2), 1)):
        self.n_features_to_select = n_features_to_select
        self.m = m
        self.dist_func = dist_func
        script_path = os.path.abspath(__file__)
        self._relief = jl.include(script_path[:script_path.rfind('/')] +
                                  "/relief2.jl")
Exemple #29
0
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):
Exemple #30
0
import numpy as np
import os

from julia import Julia
jl = Julia(compiled_modules=False)
script_path = os.path.abspath(__file__)
jl.eval('push!(LOAD_PATH, "' + script_path[:script_path.rfind('/')] + '/")')
from julia import MBD as MBD_jl


class MBD:
    '''
    Class encapsulating the Mass-based dissimilarity metric.

    Args:
        n_features_to_select (int): Number of i-tree space partitioning models to use.

    Attributes:
        n_features_to_select (int): Number of i-tree space partitioning models to use.
    '''
    def __init__(self, num_itrees=10):
        self.num_itrees = num_itrees

    def get_dist_func(self, data):
        '''
        Get computed metric function from data.

        Args:
            data (numpy.ndarray): Matrix of training samples.

        Returns:
Exemple #31
0
"""
ASE to JuLIP.jl interface

Requires `pyjulia` package from https://github.com/JuliaPy/pyjulia
"""

import numpy as np
from ase.calculators.calculator import Calculator
from ase.optimize.optimize import Optimizer

from julia import Julia
julia = Julia()
julia.using("JuLIP")

# Workaround limitiation in PyCall that does not allow types to be called
#   https://github.com/JuliaPy/PyCall.jl/issues/319

ASEAtoms = julia.eval('ASEAtoms(a) = JuLIP.ASE.ASEAtoms(a)')
ASECalculator = julia.eval('ASECalculator(c) = JuLIP.ASE.ASECalculator(c)')
fixedcell = julia.eval('fixedcell(a) = JuLIP.Constraints.FixedCell(a)')
variablecell = julia.eval(
    'variablecell(a) = JuLIP.Constraints.VariableCell(a)')


class JulipCalculator(Calculator):
    """
    ASE-compatible Calculator that calls JuLIP.jl for forces and energy
    """
    implemented_properties = ['forces', 'energy', 'stress']
    default_parameters = {}
    name = 'JulipCalculator'
Exemple #32
0
# 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
Exemple #33
0
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()
Exemple #34
0
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")
Exemple #35
0
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