import os

def make_dir_exists(path):
    if path[-1] != '/':
        path += '/'
    try: os.makedirs(path)
    except: pass
    return path

log_file = None
print_ = print

def setup_log(log_filename):
    global log_file
    # log_file = open(args.save + 'log.txt', 'a')
    log_file = open(log_filename, 'w')

def print(*args, **kwargs):
    global log_file
    print_(*args, **kwargs)
    print_(*args, **kwargs, file=log_file)

def close_log():
    global log_file
    try: log_file.close()
    except: pass

def explained_variance(ypred,y):
    """
    Computes fraction of variance that ypred explains about y.
    Returns 1 - Var[y-ypred] / Var[y]
    interpretation:
        ev=0  =>  might as well have predicted zero
        ev=1  =>  perfect prediction
        ev<0  =>  worse than just predicting zero
    """
    return 1 - (y-ypred).var()/y.var()
    # assert y.ndim == 1 and ypred.ndim == 1
    # vary = np.var(y)
    # return np.nan if vary==0 else 1 - np.var(y-ypred)/vary
