예제 #1
0
def create_profile(time, rate_constants):
    """ Computes a concentration profile according to the *model()* function.

    Parameters
    ----------
    time : np.array
        Time array.
    rate_constants : RateConstants
        RateConstants object.

    Returns
    -------
    profile : np.array
        Concentration profile matrix.
    """

    ks = rate_constants.ks
    alphas = rate_constants.alphas

    if rate_constants.style == 'dec':
        s0 = np.ones(ks.shape[0])
    elif rate_constants.style == 'custom':
        s0 = np.zeros(ks.shape)
        for i in range(s0.shape[1]):
            s0[0, i] = alphas[i]
        s0 = s0.flatten('F')
    else:
        # assuming a starting population of 100% for the first species
        s0 = np.zeros(ks.shape[0])
        s0[0] = 1

    time = time.reshape(-1)

    # sometimes odeint encounters an overflow
    errs = scsp.geterr()
    errs['overflow'] = 'ignore'
    scsp.seterr(**errs)

    profile = odeint(model, s0, time, (rate_constants, ))

    errs['overflow'] = 'warn'
    scsp.seterr(**errs)

    if rate_constants.style == 'custom':
        profile = np.split(profile, ks.shape[1], axis=1)
        profile = np.sum(profile, axis=0)

    return profile
예제 #2
0
def test_seterr():
    entry_err = sc.geterr()
    try:
        for category, error_code in _sf_error_code_map.items():
            for action in _sf_error_actions:
                geterr_olderr = sc.geterr()
                seterr_olderr = sc.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = sc.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function, (error_code, ), action)
    finally:
        sc.seterr(**entry_err)
예제 #3
0
def test_seterr():
    entry_err = sc.geterr()
    try:
        for category in _sf_error_code_map.keys():
            for action in _sf_error_actions:
                geterr_olderr = sc.geterr()
                seterr_olderr = sc.seterr(**{category: action})
                assert_(geterr_olderr == seterr_olderr)
                newerr = sc.geterr()
                assert_(newerr[category] == action)
                geterr_olderr.pop(category)
                newerr.pop(category)
                assert_(geterr_olderr == newerr)
                _check_action(_sf_error_test_function,
                              (_sf_error_code_map[category],),
                               action)
    finally:
        sc.seterr(**entry_err)
예제 #4
0
from sys import stdout
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
from scipy import special
from cmath import *
from scipy.stats import qmc
import os
os.environ['NUMBAPRO_CUDALIB']='C:/Users/gueux/Miniconda3/envs/py36_7/Library/bin'
np.seterr(all='raise')
special.seterr(all='raise')
sobol_set = True
#sobol_set = False

# f-function related
def fp(e,p,ab,s1=0.76,s2=0.1821):
    if e == 0:
        #print('e -> 0, return value -> inf')
        #return inf
        return 0 
    else:
        exponent = 2*s2/(np.power(e/ab,s1) + np.power(e/ab,-s1))
        base = 1/np.cosh(p)
        return np.power(base, exponent)
    
def fpp(e,p,ab,s1=0.76,s2=0.1821):
    if p == 0:
        return 0
    else:
        return fp(e,p,ab,s1,s2)*p
예제 #5
0
파일: LRC.py 프로젝트: monimoyb/kendama
from numpy.linalg import norm, inv, det, matrix_power
from numpy.random import randn, randint, uniform
from math import pi, sqrt, atan2, sin, cos, floor
from controlpy.synthesis import controller_lqr_discrete_time as dlqr
import gurobipy as gp
from gurobipy import *
import scipy.sparse as sp
from scipy.linalg import block_diag
import matplotlib.pyplot as plt

from pytope import Polytope
from pytope.polytope import intersection, minkowski_sum
import multiprocessing

import scipy.special as sc
sc.seterr(all='ignore')


def DefineStabilizingController(A, B, Q, R):
    # UNTITLED2 Summary of this function goes here
    # Detailed explanation goes here

    Ks, _, _ = dlqr(A, B, Q, R)
    Ks = -Ks

    Ke, _, _ = dlqr(A, B, Q, R)
    Ke = -Ke

    return Ks, Ke

예제 #6
0
def SpectralClustering(ck_sym, sc, options, rep_factor=100 ):
    # np.set_printoptions(threshold=np.nan)
    np.seterr(all='raise')
    sc_special.seterr(all='raise')
    check_point = time()

    nn = ck_sym.shape[0]

    dn = lil_matrix((nn, nn))
    sum_ck = np.array(np.sqrt(np.sum(ck_sym, axis=0))[0])
    # check for equality of results of different data types(matrix and array)
    # a = np.array(ck_sym.todense())  # make sure that we have dense np.array
    # b = np.sqrt(np.sum(a, axis=0))
    # print(np.allclose(b, sum_ck, rtol=1e-16, atol=1e-15))
    try:
        dn.setdiag(1.0 / np.array(sum_ck)[0])
    except (ZeroDivisionError, FloatingPointError):
        print('Avoiding division by zero in dn.diag by adding eps(long double)')
        sum_ck = np.array(sum_ck, dtype=np.longdouble)
        eps = np.finfo(np.longdouble).eps
        dn.setdiag(1.0 / (np.array(sum_ck)[0] + eps))
    dn = dn.tocsc()

    del sum_ck
    if options['verbose'] > 1:
        print('Starting eigen decomposition')
    if options['spectral_eig_algo'] == 1:
        lap_n = dn * ck_sym * dn  # moved to matrix notation
        ut, s, vn = svds(lap_n, options['n_clusters'], which='LM', ncv=min(5*options['n_clusters'] + 1, nn//2 + 1))
        for i in range(options['n_clusters']):
            if(s.imag.any() != 0):
                print(i)
        kern = np.fliplr(vn).T
    elif options['spectral_eig_algo'] == 2:  # LOOKS LIKE THIS PACKAGE IS OUTDATED AND PRODUCES WRONG RESULTS.
                            # Latest tested(successfully) python version for it is 3.2
        sp_d_n = dn
        # sp_d_n = sparse.csc_matrix(dn)
        lap_n = sp_d_n.dot(sparse.csc_matrix(ck_sym)).dot(sp_d_n)
        ut, s, vn = sparsesvd(lap_n, options['n_clusters'])
        kern = vn.T
        if len(s) < options['n_clusters']:
            sp_d_n = sparse.csc_matrix(dn)
            lap_n = sp_d_n.dot(sparse.csc_matrix(ck_sym)).dot(sp_d_n)
            one, two, vn = svds(lap_n, options['n_clusters'], which='LM', ncv=100)
            kern = vn[::-1].T
    elif options['spectral_eig_algo'] == 3:  # very slow, but always correct
        # LapN = np.identity(nn) - np.dot(np.dot(DN, CKSym), DN)
        dn = dn.todense()
        lap_n = np.dot(np.dot(dn, ck_sym), dn)
        ut, s, vn = linalg.svd(lap_n, full_matrices=True, lapack_driver='gesvd')
        kern = vn[0:options['n_clusters']].T
    else:
        # **** BEGIN NON-SPARSE SVD *****
        # LapN = np.identity(nn) - np.dot(np.dot(DN, CKSym), DN)
        dn = dn.todense()
        lap_n = np.dot(np.dot(dn, ck_sym), dn)
        one, two, vn = np.linalg.svd(lap_n, full_matrices=True)  # returns U, s, vN
        kern = vn[0:options['n_clusters']].T
        # **** END NON-SPARSE SVD *****
    if options['verbose'] > 1:
        print('Done with eigen decomposition')
    del dn, ck_sym, lap_n, vn

    kern = np.array(kern, dtype=np.longdouble)
    norm_n = norm(kern, axis=1)  # FloatingPointError: underflow encountered in multiply in RMS data
    # https: // docs.scipy.org / doc / numpy / reference / generated / numpy.apply_along_axis.html
    try:
        kern_s = np.apply_along_axis(lambda a, b: a / b, 0, kern, norm_n)
    except (ZeroDivisionError, FloatingPointError):
        print('Avoiding division by zero in kern_norm by adding eps(long double)')
        eps = np.finfo(np.longdouble).eps
        kern_s = np.apply_along_axis(lambda a, b: a / b, 0, kern, norm_n + eps)

    # kerNS = np.array(kerNS, dtype=np.float64)

    # if sum(sum(abs(kern_s.imag))) > 0:
    #     print('Imaginary numbers in Laplasians,')
    #     kern_s = kern_s.real
    #     exit(-5)
    check_point = log_print(check_point, options['verbose'], '%s Eigen decomposition time : ' % options['times'])
    total_batch_size = 200*cpu_count()
    if options['verbose'] > 1:
        print('Starting K-means algorithm')
    if options['kmeans_minibatch']:
        groups = MiniBatchKMeans(n_clusters=options['n_clusters'], tol=1e-7, max_no_improvement=20, batch_size=total_batch_size,
                                 n_jobs=cpu_count()).fit_predict(kern_s)
        bestGroups = groups
        nmi_batch = []
        iter_counter = total_batch_size
    else:
        bestNMI, bestGroups, nmi_batch, iter_counter = simple_kmeans_par(kern_s, sc, options)
    if options['verbose'] > 1:
        print('Done with K-means algorithm')
    # import seaborn as sns
    # sns.set_style('whitegrid')
    # sns.kdeplot(NMI_batch, bw=0.000000001)
    # sns.kdeplot(NMI_batch)
    # max1 = NMI_batch.max()
    # min1 = NMI_batch.min()
    bestGroups += 1  # add 1 to all elements since bestMap and further processing requires 1 as minimum index
    check_point = log_print(check_point, options['verbose'], '%s Kmeans(with NMI) time : ' % options['times'])
    return bestGroups, nmi_batch, iter_counter
예제 #7
0
################################################################################
# lib.py contained all the function needed to run Analytic_filtering,
# Filtering_function, Histogram_computation, Test_distribution & Test_parralel
#
# Contact : Sullivan MARAFICO                [email protected]
################################################################################
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy import special, interpolate, integrate, misc, stats
from threading import Thread
import multiprocessing as mp

Nlim = -4.  # log_lambda minimum for computing the histogram (if too small, computations can fail)

special.seterr(all="ignore")


def TestPDF(total, precision):
    '''Test if total(sum of PDF) is smaller or bigger than 1 +- 2*precision
    If yes, it shows a warning with the values of total'''

    if total < 1 - 2 * precision:
        print(
            "/!\ WARNING : Sum of probabilities < 1-2*precision (cf. TestPDF)")
        print("/!\ 1-precision = " + str(1 - precision) + "   | Sum = " +
              str(total))
        return False

    if total > 1 + 2 * precision:
        print("/!\ WARNING : Sum of probabilities > 1 (cf. TestPDF)")
예제 #8
0
from scipy.optimize import linprog
import numpy as np
import pandas as pd
from scipy import stats
import scipy.special as sc
sc.seterr(all="ignore")  # TODO: suppress ALL warnings


def init_alpha(budget, n_treatments):
    alpha = np.random.uniform(-budget, 0, size=None)
    return alpha


def init_beta(budget, n_treatments):
    beta = np.random.uniform(-budget, budget, size=n_treatments)
    return beta


# Output dimensions: (n_subjects, n_treatments)
def get_price_matrix(alpha, beta, pte_matrix):
    price_matrix = alpha * pte_matrix + beta
    return price_matrix


# Solve linear programming problem to get utility-maximizing demands. Dimensions: (n_subjects, n_treatments)
def get_demand_matrix(wtp_matrix, pte_matrix, price_matrix, subject_budgets,
                      rct_treatment_probabilities, epsilon):
    # Create empty matrix for filling
    demand_matrix = []

    # Solve problem for each individual
예제 #9
0
import numpy as np
import math
from scipy.optimize import curve_fit
from scipy.special import erf, seterr
from scipy.stats import kurtosis, skew
from astropy.modeling import models, fitting
import scipy.integrate as integrate
import warnings

from utils.run_functions import psnr, brightness_error
from utils.run_functions import rms
from utils.structures import DatabaseItem

seterr(all='ignore')  # suppress fitting errors
warnings.simplefilter("ignore")  # suppress fitting warnings


class PointCluster(object):
    ''' Object representing single cluster of pixels, fits functions as well as produces output for object '''
    def __init__(self, points, image):
        self.points = points
        self.correct_fit = False
        self.peak_point = None
        self.header_data = None
        self.background_data = None
        self.squared_data = None
        self.image = image
        self.kurtosis = None
        self.skew = None
        self.psnr = None
        self.show_object_fit = False
예제 #10
0
    nd = args.nd
    na = args.na
    filebase = args.filebase
    output = args.output
    quasi = args.quasi
    integ = args.integ
    rank = args.rank
    seed = args.seed
    dep = args.dep
    skip = args.skip
    d0 = args.d0
    d1min = 1
    d1max = args.dmax
    np.random.seed(seed)
    np.seterr(all='ignore')
    seterr(all='ignore')

    #We should find the lcc of the network and discard the rest.
    start = timeit.default_timer()
    eta, nu, k, G = get_network(n, nr, na)

    if args.type == 0:
        row, col = np.where(eta[::2] - nu[::2] != 0)
        data = (eta[::2] - nu[::2])[row, col]
        A = csr_matrix((data, (row, col)), shape=(2 * nr, n), dtype=int)
        adj = A.T.dot(A)
        g = nx.convert_matrix.from_scipy_sparse_matrix(adj)

    if args.type == 1:
        g = nx.gnm_random_graph(n, nr, seed=seed)
        adj = nx.adjacency_matrix(g)