Beispiel #1
0
def histogram(filepath, k=11):
    c = cooler.Cooler(filepath)
    bin_size = 500000
    count_bins_chr1 = math.ceil(c.chromsizes[0] / bin_size)
    contact_matrix = c.matrix(balance=False)[:count_bins_chr1, :count_bins_chr1]
    diag = get_upper_k_diagonal(contact_matrix, k)
    hist = np.histogram(np.array(diag))
    plt.hist(hist)
Beispiel #2
0
def refine(*args):
    """
    function [values, giveUp] = refine(op, values, pref)
    #REFINE   Refinement method for CHEBTECH2 construction.
    #   VALUES = REFINE(OP, VALUES, PREF) determines the new VALUES of the operator
    #   OP to be checked for happiness in the CHEBTECH2 construction process. The
    #   exact procedure used is determined by PREF.REFINEMENTFUNCTION.
    #
    #   [VALUES, GIVEUP] = REFINE(OP, VALUES, PREF) returns also a binary GIVEUP
    #   flag where TRUE means the refinement procedure has failed (typically when
    #   the maximum number of points, PREF.MAXLENGTH, has been reached).
    #
    #   The two built-in refinement strategies are 'NESTED' and 'RESAMPLING'. The
    #   former makes use of the nested property of the 2nd-kind grid by taking N
    #   (the number of points) to be 2^(4:16) + 1 and doesn't resample previously
    #   evaluated values. The latter uses grids of the form 2^(4:6 6:.5:16) + 1 and
    #   resamples all of the values each time N is increased. The 'RESAMPLING'
    #   option should be used for functions which are not sampleable, for example,
    #   anything that depends on the length of the input to OP.
    #
    #   Alternative refinement strategies can be used by passing a function handle
    #   in the PREF.REFINEMENTSTRATEGY field. The function handle should point to a
    #   function with the template [VALUES, GIVEUP] = @(OP, VALUES, PREF) ... which
    #   accepts a function handle OP, previously sampled values VALUES of OP at a
    #   2nd-kind Chebyshev grid, and PREF, a preference structure containing
    #   CHEBTECH preferences. It should return either a new set of VALUES
    #   (typically on a finer grid) or set the GIVEUP flag to TRUE.

    # Copyright 2016 by The University of Oxford and The Chebfun Developers. 
    # See http://www.chebfun.org/ for Chebfun information.
    """

    op = args[0]

    # No values were given:
    if len(args) < 2:
        values = np.array([])
    else:
        values = args[1]

    # Obtain some preferences:
    if len(args) < 3:
        pref = chebtech.techPref();
    else:
        pref = args[2]

    # Grab the refinement function from the preferences:
    refFunc = pref.refinementFunction;

    # Decide which refinement to use:
    if ( strcmpi(refFunc, 'nested') )
        # Nested ('single') sampling:
        [values, giveUp] = refineNested(op, values, pref);
    elseif ( strcmpi(refFunc, 'resampling') )
        # Double sampling:
        [values, giveUp] = refineResampling(op, values, pref);
Beispiel #3
0
    def trumpet_positions(self, current, voltage):
        volts = np.array(voltage)
        amps = np.array(current)

        if self.simulation_options["find_in_range"] != False:
            dim_volts = self.e_nondim(volts)
            search_idx = tuple(
                np.where(
                    (dim_volts > self.simulation_options["find_in_range"][0]) &
                    (dim_volts < self.simulation_options["find_in_range"][1])))
            #fig, ax=plt.subplots(1,1)
            #ax.plot(dim_volts, amps)
            volts = volts[search_idx]
            amps = amps[search_idx]

            #print(self.simulation_options["find_in_range"])
            #ax.plot(volts, amps)
            #plt.show()
        max_pos = volts[np.where(amps == max(amps))]
        min_pos = volts[np.where(amps == min(amps))]
        return max_pos, min_pos
Beispiel #4
0
 def fit(self, x, y, w=None):
     if w is None:
         w = np.ones(len(y)) / len(y)
     data = zip(x, y, w)
     data = sorted(data, key=lambda s: s[0])
     [x, y, w] = zip(*data)
     y = np.array(y)
     w = np.array(w)
     correct = np.zeros((2, len(y)))  # 0 row for x < v, 1 row for x >= v
     for i in range(len(y)):
         w_front = w[:i]
         w_back = w[i:]
         correct[0, i] += np.sum(w_front[y[:i] == 1]) + np.sum(
             w_back[y[i:] == -1])
         correct[1, i] += np.sum(w_front[y[:i] == -1]) + np.sum(
             w_back[y[i:] == 1])
     idx = np.argmax(correct, axis=1)
     if correct[0, int(idx[0])] > correct[1, int(idx[1])]:
         self.sign = "smaller"
         self.thres = x[idx[0]]
     else:
         self.sign = "equal to or bigger"
         self.thres = x[idx[1]]
Beispiel #5
0
def create_signature_block(author_name):
    """Create signature block for given author_name.

    :param str author_name: author's full name
        Example:
            author_name = "Ellis, John R"

    :return: string representing phonetic block for full_name
        Example:
            u'ELj'
    """
    try:
        name = {'author_name': author_name}
        signature_block = block_phonetic(
            np.array([name], dtype=np.object).reshape(-1, 1),
            threshold=0,
            phonetic_algorithm='nysiis')
        return signature_block[0]
    except (IndexError, KeyError) as err:
        print "Couldn't create signature: {0} in '{1}'".format(err, name)
Beispiel #6
0
from tensorflow.python.keras.models import Sequential
from tensorflow.python.layers.core import Dense
from numpy import np

data = np.array([
    [
        5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5,
        1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2,
        5.1, 3.5
    ],
    [
        4.9, 3., 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5,
        1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2,
        5.1, 3.5
    ],
    [
        4.7, 3.2, 1.3, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5,
        1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2,
        5.1, 3.5
    ],
    [
        4.6, 3.1, 1.5, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5,
        1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2, 5.1, 3.5, 1.4, 0.2,
        5.1, 3.5
    ],
])
labels = np.array([0, 1, 0, 1])
print('------A. Training------')

model = Sequential()
layer1 = Dense(200, activation='relu', input_dim=4)
Beispiel #7
0
def cartesian_to_polar(pos):
    r = np.linalg.norm(pos)
    t = get_cartesian_angle(pos[0], pos[1])
    
    return np.array([r, t])
Beispiel #8
0
def polar_to_cartesian(pol):
    r, t = pol[0], pol[1]
    coord = r * np.array([np.cos(t), np.sin(t)])
    return coord
Beispiel #9
0
 def __init__(self, dictionary):
     self.cuisine = np.array(dictionary["data"]).reshape(16, )
     self.price = dictionary["price"]
     self.location = np.array(dictionary["location"]).reshape(2, )
a.invert()  #bitwise_not
a.left_shift()
a.right_shift()

#strings methods
#il existe des méthodes pour les
#types numpy.string_ et numpy.unicodes
#on peut voir ça sur le site.
#Elles sont similaires aux
#methodes python de base

#------------------------
#fonctions mathématiques:
#------------------------
#trigo
a = np.array([0, 30, 45, 60, 90])
print(np.sin(a * np.pi / 180))
print(np.cos(a * np.pi / 180))
print(np.tan(a * np.pi / 180))
print(np.arcsin(a * np.pi / 180))
print(np.arcos(a * np.pi / 180))
print(np.arctan(a * np.pi / 180))
inv = pn.arcsin(np.sin(a * np.pi / 180))
print(np.degrees(inv))  #par défaut les valeurs sont en radian

#rounding
print(np.around(a))
print(np.around(a, decimals=1))
print(np.around(a, decimals=-1))

print(np.floor(a))
Beispiel #11
0
def optimizePortfolio(df_rets, list_min, list_max, list_price_target,
                      target_risk, direction="long"):

    naLower = np.array(list_min)
    naUpper = np.array(list_max)
    naExpected = np.array(list_price_target)

    b_same_flag = np.all(naExpected == naExpected[0])
    if b_same_flag and (naExpected[0] == 0):
        naExpected = naExpected + 0.1
    if b_same_flag:
        na_randomness = np.ones(naExpected.shape)
        target_risk = 0
        for i in range(len(na_randomness)):
            if i % 2 == 0:
                na_randomness[i] = -1
        naExpected = naExpected + naExpected * 0.0000001 * na_randomness

    (fMin, fMax) = getRetRange(df_rets.values, naLower, naUpper,
                               naExpected, direction)

    # Try to avoid intractible endpoints due to rounding errors """
    fMin += abs(fMin) * 0.00000000001
    fMax -= abs(fMax) * 0.00000000001

    if target_risk == 1:
        (naPortWeights, fPortDev, b_error) = OptPort(df_rets.values, fMax, naLower, naUpper, naExpected, direction)
        allocations = _create_dict(df_rets, naPortWeights)
        return {'allocations': allocations, 'std_dev': fPortDev, 'expected_return': fMax, 'error': b_error}

    fStep = (fMax - fMin) / 50.0

    lfReturn = [fMin + x * fStep for x in range(51)]
    lfStd = []
    lnaPortfolios = []

    for fTarget in lfReturn:
        (naWeights, fStd, b_error) = OptPort(df_rets.values, fTarget, naLower, naUpper, naExpected, direction)
        if not b_error:
            lfStd.append(fStd)
            lnaPortfolios.append(naWeights)
        else:
            # Return error on ANY failed optimization
            allocations = _create_dict(df_rets, np.zeros(df_rets.shape[1]))
            return {'allocations': allocations, 'std_dev': 0.0,
                    'expected_return': fMax, 'error': True}

    if len(lfStd) == 0:
        (naPortWeights, fPortDev, b_error) = OptPort(df_rets.values, fMax, naLower, naUpper, naExpected, direction)
        allocations = _create_dict(df_rets, naPortWeights)
        return {'allocations': allocations, 'std_dev': fPortDev, 'expected_return': fMax, 'error': True}

    f_return = lfReturn[lfStd.index(min(lfStd))]

    if target_risk == 0:
        naPortWeights = lnaPortfolios[lfStd.index(min(lfStd))]
        allocations = _create_dict(df_rets, naPortWeights)
        return {'allocations': allocations, 'std_dev': min(lfStd), 'expected_return': f_return, 'error': False}

    # Otherwise try to hit custom target between 0-1 min-max risk
    fTarget = f_return + ((fMax - f_return) * target_risk)

    (naPortWeights, fPortDev, b_error) = OptPort(df_rets.values, fTarget, naLower, naUpper, naExpected, direction)
    allocations = _create_dict(df_rets, naPortWeights)
    return {'allocations': allocations, 'std_dev': fPortDev, 'expected_return': fTarget, 'error': b_error}
Beispiel #12
0
def getOptPort(rets, f_target, l_period=1, naLower=None, naUpper=None, lNagDebug=0):
    """
    @summary Returns the Markowitz optimum portfolio for a specific return.
    @param rets: Daily returns of the various stocks (using returnize1)
    @param f_target: Target return, i.e. 0.04 = 4% per period
    @param l_period: Period to compress the returns to, e.g. 7 = weekly
    @param naLower: List of floats which corresponds to lower portfolio% for each stock
    @param naUpper: List of floats which corresponds to upper portfolio% for each stock
    @return tuple: (weights of portfolio, min possible return, max possible return)
    """

    # Attempt to import library """
    try:
        pass
        import nagint as nag
    except ImportError:
        print 'Could not import NAG library'
        print 'make sure nagint.so is in your python path'
        return ([], 0, 0)

    # Get number of stocks """
    lStocks = rets.shape[1]

    # If period != 1 we need to restructure the data """
    if(l_period != 1):
        rets = getReindexedRets(rets, l_period)

    # Calculate means and covariance """
    naAvgRets = np.average(rets, axis=0)
    naCov = np.cov(rets, rowvar=False)

    # Special case for None == f_target"""
    # simply return average returns and cov """
    if(f_target is None):
        return naAvgRets, np.std(rets, axis=0)

    # Calculate upper and lower limits of variables as well as constraints """
    if(naUpper is None):
        naUpper = np.ones(lStocks)  # max portfolio % is 1

    if(naLower is None):
        naLower = np.zeros(lStocks)  # min is 0, set negative for shorting
    # Two extra constraints for linear conditions"""
    # result = desired return, and sum of weights = 1 """
    naUpper = np.append(naUpper, [f_target, 1.0])
    naLower = np.append(naLower, [f_target, 1.0])

    # Initial estimate of portfolio """
    naInitial = np.array([1.0 / lStocks] * lStocks)

    # Set up constraints matrix"""
    # composed of expected returns in row one, unity row in row two """
    naConstraints = np.vstack((naAvgRets, np.ones(lStocks)))

    # Get portfolio weights, last entry in array is actually variance """
    try:
        naReturn = nag.optPort(naConstraints, naLower, naUpper,
                               naCov, naInitial, lNagDebug)
    except RuntimeError:
        print 'NAG Runtime error with target: %.02lf' % (f_target)
        return (naInitial, sqrt(naCov[0][0]))
    #return semi-junk to not mess up the rest of the plot

    # Calculate stdev of entire portfolio to return"""
    # what NAG returns is slightly different """
    fPortDev = np.std(np.dot(rets, naReturn[0, 0:-1]))

    # Show difference between above stdev and sqrt NAG covariance"""
    # possibly not taking correlation into account """
    #print fPortDev / sqrt(naReturn[0, -1])

    # Return weights and stdDev of portfolio."""
    #  note again the last value of naReturn is NAG's reported variance """
    return (naReturn[0, 0:-1], fPortDev)
Beispiel #13
0
 def get_hist(self) -> np.array:
     intIm = np.round(255 * self.im)
     return np.array([np.count_nonzero(intIm == x) for x in range(255)])