def Equaliterality(AAAB14):
    """ Calculates the Equaliterality of the Tetrahedra.
		Specific for Ion Environments project. """
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    L1 = GetInd(Head, 'L1')
    L2 = GetInd(Head, 'L2')
    L4 = GetInd(Head, 'L4')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'Equilaterality')
    Data.append(Head)
    for item in Tail:
        A = dc(item[L1])
        B = dc(item[L2])
        C = dc(item[L4])
        # print A, B, C
        Mn = (A + B + C) / dc(3)
        SqMn = Mn**2
        AA = (A - B)**2
        BB = (A - C)**2
        CC = (B - C)**2
        Num = AA + BB + CC
        Den = dc(3) * SqMn
        ans = Num / Den
        Equa = round(ans, 4)
        item.insert(SStruct, str(Equa))
        # print (item)
        Data.append(item)
    return Data
def Height(AAAB14):
    """ Calculates the Height of Tetrahedra.
		Specific for Ion Environments project. """
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    L1 = GetInd(Head, 'L1')
    L2 = GetInd(Head, 'L2')
    L4 = GetInd(Head, 'L4')
    Vl = GetInd(Head, 'Volume')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'Height')
    Data.append(Head)
    for item in Tail:
        A = dc(item[L1])
        B = dc(item[L2])
        C = dc(item[L4])
        Vol = dc(item[Vl])
        S = (A + B + C) / dc(2)
        SA = S - A
        SB = S - B
        SC = S - C
        a = (S * (SA * SB * SC))
        area = numpy.sqrt(a)
        ht = (3 * Vol) / area
        Height = round(ht, 4)
        item.insert(SStruct, str(Height))
        Data.append(item)
    return Data
def return_B(K, m):
    muller = gamma(-1 + ((2j * math.pi * m) / math.log(2)))
    multiplier_real = dc(muller.real)
    multiplier_imag = dc(muller.imag)
    A_real, A_img = return_A(K, m)
    term_real = (multiplier_real * A_real) - (multiplier_imag * A_img)
    term_img = (multiplier_imag * A_real) + (multiplier_real * A_img)
    return term_real, term_img
Пример #4
0
    def parse_player(self, response):

        try:
            g, h, w = response.css(
                "span:nth-child(5) .entry-crumb , .row-2 .column-2 , .row-3 .column-2"
            ).xpath("text()").extract()

            n = response.css('p:nth-child(4)').xpath('text()').extract_first()
            h = h.split()
            w = int(w.split()[0])

        except ValueError as v:

            g = response.css("span:nth-child(5) .entry-crumb").xpath(
                "text()").extract_first()
            n = response.xpath(
                '//p[preceding-sibling::h3/strong[text()="Born Name"]]/text()'
            ).extract_first()
            h = response.xpath(
                '//p[preceding-sibling::h3/strong[text()="Height"]]/text()'
            ).extract_first()
            w = response.xpath(
                '//p[preceding-sibling::h3/strong[text()="Weight"]]/text()'
            ).extract_first()

            h = h.split('or')[0].split()
            w = int(w.split('or')[0].split()[0])

        if 'ft' in h:

            hi = dc(int(h[0])) * 12
            if 'in' in h:
                if not h[-2][-1].isdigit():
                    h[-2] = float(h[-2][:-1]) + numeric(h[-2][-1])

                hi += dc(h[-2])

            h = round(dc(hi) * dc(2.54), 2)

        if 'male' or 'female' in g.lower():
            g = g.split()[0]

        # id of the player
        i = response.url.split('/')[-1]

        # url
        url = response.url

        print("====================>", self.count)

        yield {
            'id': i,
            'name': n,
            'gender': g,
            'height': h,
            'weight': w,
            'url': url
        }
def TriangleArea(A, B, C):
    """ Calculates area of a triangle
		using lengths of sides as input."""
    A, B, C = dc(A), dc(B), dc(C)
    S = (A + B + C) / 2
    SA = S - A
    SB = S - B
    SC = S - C
    a = (S * (SA * SB * SC))
    area = numpy.sqrt(a)
    Area = round(area, 4)
    return Area
Пример #6
0
    def results(self, times='all', t_precision=12, **kwargs):
        r"""
        Fetches the calculated quantity from the algorithm and returns it as
        an array.

        Parameters
        ----------
        times : scalar or list
            Time steps to be returned. The default value is 'all' which results
            in returning all time steps. If a scalar is given, only the
            corresponding time step is returned. If a range is given
            (e.g., 'range(0, 1, 1e-3)'), time steps in this range are returned.

        t_precision : integer
            The time precision (number of decimal places). Default value is 12.

        Notes
        -----
        The keyword steps is interpreted in the same way as times.
        """
        if 'steps' in kwargs.keys():
            times = kwargs['steps']
        t_pre = t_precision
        quantity = self.settings['quantity']
        q = [k for k in list(self.keys()) if quantity in k]
        if times == 'all':
            t = q
        elif type(times) in [float, int]:
            n = int(-dc(str(round(times, t_pre))).as_tuple().exponent *
                    (round(times, t_pre) != int(times)))
            t_str = (str(int(round(times, t_pre) * 10**n)) + ('e-' + str(n)) *
                     (n != 0))
            t = [k for k in q if t_str == k.split('@')[-1]]
        elif 'range' in times:
            t = times.replace(' ', '')
            t = t[6:-1]
            t = t.split(',')
            out = np.arange(float(t[0]), float(t[1]), float(t[2]))
            out = np.append(out, float(t[1]))
            out = np.unique(out)
            out = np.around(out, decimals=t_pre)
            t = []
            for i in out:
                n = int(-dc(str(round(i, t_pre))).as_tuple().exponent *
                        (round(i, t_pre) != int(i)))
                j = (str(int(round(i, t_pre) * 10**n)) + ('e-' + str(n)) *
                     (n != 0))
                t_str = [k for k in q if j == k.split('@')[-1]]
                t += (t_str)
        d = {k: self[k] for k in t}
        return d
Пример #7
0
def get_account_value(selected_account, all_assets):
    account_value = all_assets.aggregate(
        Sum('value'))['value__sum'] or dc(0.00)
    selected_account.value = account_value
    selected_account.save()

    return account_value
Пример #8
0
def new_asset(request, account_id):
    if request.method == "POST":
        asset_form = NewAssetForm(request.POST)

        if asset_form.is_valid():
            account = AssetAccount.objects.get(pk=account_id)
            asset = asset_form.save(commit=False)
            stock = yf.Ticker(
                asset.ticker)  #exception for if not a valid stock
            asset.price = stock.info['currentPrice']
            asset.value = dc(asset.price) * asset.shares
            asset.account = account
            asset.save()

            updated_assets = Asset.objects.filter(account=account)
            history = AccountHistory.objects.get(account=account)
            history.value = get_account_value(account, updated_assets)
            history.save()

            return redirect(
                reverse('finance_app:account-detail',
                        kwargs={'account_id': account_id}))

    else:
        asset_form = NewAssetForm()
        return render(request, 'finance_app/asset_new.html',
                      {'asset_form': asset_form})
Пример #9
0
def budget_dashboard(request):
    try:  #need a test for this
        expenses = latest_months_expenses()

    except ObjectDoesNotExist:
        expenses = Expense.objects.none()

    total_transactions = Transaction.objects.all().aggregate(
        Sum('inflow'))['inflow__sum'] or dc(0.00)
    total_allocations = expenses.aggregate(
        Sum('allocated'))['allocated__sum'] or dc(0.00)
    unbudgeted = total_transactions - total_allocations
    context = {
        'expenses': expenses,
        'unbudgeted': unbudgeted,
    }

    return render(request, 'budget_app/dashboard.html', context)
Пример #10
0
def min_max_points(df):
    diff_lwx = np.diff(split_leftwrist_x(df))
    diff_rwx = np.diff(split_rightwrist_x(df))
    diff_lwy = np.diff(split_leftwrist_y(df))
    diff_rwy = np.diff(split_rightwrist_y(df))

    x = [diff_lwx, diff_lwy, diff_rwx, diff_rwy]
    min_max = []

    for i in x:
        l = len(i)
        j = 0
        while j < l:
            min1 = fc.minimum(i[j:j + math.ceil(l / 3)])
            max1 = fc.minimum(i[j:j + math.ceil(l / 3)])
            dev = dc(max1) - dc(min1)
            min_max.append(dev)
            j = j + math.ceil(l / 3)
    return pd.DataFrame(min_max).transpose()
def SumSA(AAAB14):
    """ Calculates the Surface Area of the Tetrahedra.
		Specific for the Ion Environments Project. """
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    ta1 = GetInd(Head, 'Triangle1')
    ta2 = GetInd(Head, 'Triangle2')
    ta3 = GetInd(Head, 'Triangle3')
    ta4 = GetInd(Head, 'Triangle4')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'Simplex_SurfArea')
    Data.append(Head)
    for item in Tail:
        A, B, C, D = dc(item[ta1]), dc(item[ta2]), dc(item[ta3]), dc(item[ta4])
        Sum = (A + B + C + D)
        Sum = round(Sum, 4)
        item.insert(SStruct, str(Sum))
        Data.append(item)
    return Data
Пример #12
0
def MACDR2Test(pricesData, macd, signalLine):
    periods = getTradingPeriods(macd, signalLine)
    profitRateList = []
    successList = []
    for period in periods:
        totalTrade = getTotalTradesInAPeriod(pricesData, macd, signalLine,
                                             period)
        if totalTrade is not None:
            profitRate = totalTrade.getProfitRate(pricesData)
            profitRateList.append(profitRate)
            if profitRate > 0:
                successList.append(1)
            else:
                successList.append(0)

    if len(profitRateList) > 0:
        return np.mean(successList), np.mean(profitRateList)
    else:
        #return None, None
        return dc(0), dc(0)
def Triangle4(AAAB14):
    """ Calculates the Area of the Triangle.
		Specific for Ion Environments project."""
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    L1 = GetInd(Head, 'L1')
    L3 = GetInd(Head, 'L2')
    L5 = GetInd(Head, 'L4')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'Triangle4')
    Data.append(Head)
    for item in Tail:
        A = dc(item[L1])
        B = dc(item[L3])
        C = dc(item[L5])
        Area = TriangleArea(A, B, C)
        # print (Area)
        item.insert(SStruct, str(Area))
        Data.append(item)
    return Data
def AvgTF(AAAB14):
    """ Calculates the Average of Temperature Factors.
		Specific for Ion Environments project. """
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    # First get Index and then insert into header
    TF1 = GetInd(Head, 'TF1')
    TF2 = GetInd(Head, 'TF2')
    TF3 = GetInd(Head, 'TF3')
    TF4 = GetInd(Head, 'TF4')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'AvgTF')
    Data.append(Head)
    for item in Tail:
        A, B, C, D = dc(item[TF1]), dc(item[TF2]), dc(item[TF3]), dc(item[TF4])
        Avg = (A + B + C + D) / dc(4.0)
        Avg = round(Avg, 4)
        item.insert(SStruct, str(Avg))
        Data.append(item)
    return Data
Пример #15
0
 def _update_settings_and_docs(self, dc):
     if isinstance(dc, type):  # If dc is class then instantiate it
         dc = dc()
     self.__doc__ = dc.__doc__
     # if dc is a dataclass object.  This step is only necessary to support
     # Python 3.6 which doesn't have the dataclasses module
     if hasattr(dc, '__dict__'):
         dc = copy.deepcopy(dc.__dict__)
     else:
         dc = copy.deepcopy(dc)
     for item in dc.keys():
         self[item] = dc[item]
Пример #16
0
def update_stock_values(account_id):
    account_to_update = AssetAccount.objects.get(pk=account_id)
    account_assets = Asset.objects.filter(account=account_to_update)
    value_list = []

    for a in account_assets:
        s = yf.Ticker(a.ticker).info['currentPrice']
        a.price = s
        a.value = a.shares * dc(a.price)
        value_list.append(a.value)
        a.save()

    account_to_update.value = sum(value_list)
    account_to_update.save()
Пример #17
0
    def _nbr_to_str(self, nbr, t_pre=None):
        r"""
        Converts a scalar into a string in scientific (exponential) notation
        without the decimal point.

        Parameters
        ----------
        nbr : scalar
            The number to be converted into a scalar.

        t_precision : integer
            The time precision (number of decimal places). Default value is 12.
        """
        if t_pre is None:
            t_pre = self.settings['t_precision']
        n = int(-dc(str(round(nbr, t_pre))).as_tuple().exponent *
                (round(nbr, t_pre) != int(nbr)))
        nbr_str = (str(int(round(nbr, t_pre)*10**n)) + ('e-'+str(n))*(n != 0))
        return nbr_str
Пример #18
0
def nbr_to_str(nbr, t_precision):
    r"""
    Converts a scalar into a string in scientific (exponential) notation
    without the decimal point.

    Parameters
    ----------
    nbr : scalar
        The number to be converted into a scalar.

    t_precision : integer
        The time precision (number of decimal places). Default value is 12.
    """
    from decimal import Decimal as dc
    n = int(-dc(str(round(nbr, t_precision))).as_tuple().exponent *
            (round(nbr, t_precision) != int(nbr)))
    nbr_str = (str(int(round(nbr, t_precision) * 10**n)) + ('e-' + str(n)) *
               (n != 0))
    return nbr_str
Пример #19
0
    def _nbr_to_str(self, nbr, t_pre=None):
        r"""
        Converts a scalar into a string in scientific (exponential) notation
        without the decimal point.

        Parameters
        ----------
        nbr : scalar
            The number to be converted into a scalar.
        t_precision : integer
            The time precision (number of decimal places). Default value is 12.

        """
        if t_pre is None:
            t_pre = self.settings['t_precision']
        n = int(-dc(str(round(nbr, t_pre))).as_tuple().exponent *
                (round(nbr, t_pre) != int(nbr)))
        nbr_str = (str(int(round(nbr, t_pre) * 10**n)) + ('e-' + str(n)) *
                   (n != 0))
        return nbr_str
def Omega(AAAB14):
    """ Calculates the Solid Angle Omega for the Vertex that represents
		the HETATM.
		Specific for Ion Environments project. """
    Data = []
    Head = AAAB14[0]
    Tail = AAAB14[1:]
    L1 = GetInd(Head, 'L1')
    L2 = GetInd(Head, 'L2')
    L3 = GetInd(Head, 'L3')
    L4 = GetInd(Head, 'L4')
    L5 = GetInd(Head, 'L5')
    L6 = GetInd(Head, 'L6')
    SStruct = GetInd(Head, 'SStruct')
    Head.insert(SStruct, 'Omega')
    Data.append(Head)
    for item in Tail:
        l1 = dc(item[L1])
        l2 = dc(item[L2])
        l3 = dc(item[L3])
        l4 = dc(item[L4])
        l5 = dc(item[L5])
        l6 = dc(item[L6])
        # print (l1, l2, l3, l4, l5, l6)
        try:
            A = ((l5**2) + (l6**2) - (l4**2))
            a = (2 * l5 * l6)
            A = acos(A / a)
            B = ((l5**2) + (l3**2) - (l1**2))
            b = (2 * l5 * l3)
            B = acos(B / b)
            C = ((l6**2) + (l3**2) - (l2**2))
            c = (2 * l3 * l6)
            C = acos(C / c)
            S = (A + B + C) / 2.0
            val = tan(S / 2) * tan((S - A) / 2) * tan((S - B) / 2) * tan(
                (S - C) / 2)
            if val <= 0:
                val = abs(val)
        except ValueError:
            val = 0
        omega = sqrt(val)
        omega = 4 * atan(omega)
        Omega = degrees(omega)
        Omega = round(omega, 4)
        item.insert(SStruct, str(Omega))
        Data.append(item)
    return Data
def AAAB14(listFilePaths, ion_abbr, HeadList, NewList, OutLocDataFile,
           OutLocCountFile):
    """ Returns a list of lists where the vertex is AAAB abd the edge lengths
		are less than or equal to 14 A.
		Specific for Ion Environments project. """
    AAAB14 = []
    Counts = []
    for item in listFilePaths:
        entry = item.split('/')
        entry = entry[-1]
        pdbid = entry[0:4]
        chain = entry[5]
        dotloc = entry.index('.')
        pdbid_het = entry[0:dotloc]
        L1 = (HeadList.index('L1'))
        L2 = (HeadList.index('L2'))
        L3 = (HeadList.index('L3'))
        L4 = (HeadList.index('L4'))
        L5 = (HeadList.index('L5'))
        L6 = (HeadList.index('L6'))

        Fh = open(item, "r")
        lines = [i.strip() for i in Fh.readlines()]
        lineCount = 0
        AAABCount = 0
        AAAB14Count = 0
        for line in lines:
            lineCount = lineCount + 1
            if "AAAB" in line:
                AAABCount = AAABCount + 1
                line = line.split()
                if (dc(line[L1]) <= 14.00) and (dc(line[L2]) <= 14.00) and (dc(
                        line[L3]) <= 14.00) and (dc(line[L4]) <= 14.00) and (
                            dc(line[L5]) <= 14.00) and (dc(line[L6]) <= 14.00):
                    line.insert(0, pdbid_het)
                    AAAB14Count = AAAB14Count + 1
                    AAAB14.append(line)
        Fh.close()
        Cnt_List = [pdbid_het, lineCount, AAABCount, AAAB14Count]
        Counts.append(Cnt_List)
    AAAB14.insert(0, NewList)
    Counts.insert(0, ["PDBID", "Line_Count", "AAABCount", "AAAB14Count"])
    List_to_CSV(AAAB14, OutLocDataFile)
    List_to_CSV(Counts, OutLocCountFile)
    return AAAB14
def return_A(K, m):
    imag_comp = dc((2 * math.pi * m) / math.log(2))
    prod_real = dc(-(imag_comp * imag_comp))
    prod_imag = dc(-imag_comp)
    outer_k_sum_real = dc(1)
    outer_k_sum_imag = dc(0)
    for k in range(1, K + 1):
        prod_real_temp = prod_real
        prod_img_temp = prod_imag
        for i in range(1, k - 1):
            prod_real = (prod_real_temp * i) - (prod_img_temp * imag_comp)
            prod_imag = (prod_img_temp * i) + (prod_real_temp * imag_comp)
        denom = dc(math.factorial(k))
        prod_div_real = (prod_real / denom)
        prod_div_imag = (prod_imag / denom)
        outer_k_sum_real += prod_div_real
        outer_k_sum_imag += prod_div_imag
    return outer_k_sum_real, outer_k_sum_imag
Пример #23
0
 def make_commision(self, amount, order):
     tota_com = (amount * Commision_Rate) / 100
     # count = 0
     # user = self.parent if self.parent else None
     # for i in range(Limit_Upline):
     #     if user is None:
     #         break
     #     count += 1
     com = tota_com / Limit_Upline
     user = self.parent if self.parent else None
     for i in range(Limit_Upline):
         if user is None:
             break
         wallet, created = Wallet.objects.get_or_create(user=user)
         if not WalletHistory.objects.filter(wallet=wallet,
                                             order=order).exists():
             wh = WalletHistory(wallet=wallet,
                                order=order,
                                prev_bal=wallet.bal,
                                amount=com)
             wallet.bal += dc(com)
             wh.save()
         wallet.save()
         user = user.parent
Пример #24
0
 def save(self, commit=True):
     m = super(RequestForm, self).save(commit=False)
     if commit:
         m.user.profile.bal += dc(self.cleaned_data['amount'])
         m.save()
     return m
Пример #25
0
class PaymentRequest(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(validators=[OnlyPast], verbose_name='Payment Date')
    amount = models.DecimalField(max_digits=10, decimal_places=0, validators=[MinValueValidator(dc(1000))], verbose_name='Request For Amount')
    type = models.PositiveSmallIntegerField(choices=PAYMENT_MODE, verbose_name='Payment Mode')
    deposit = models.ForeignKey(Bank, on_delete=models.CASCADE, verbose_name='Deposit Bank Name')
    ref = models.CharField(max_length=255, verbose_name='Bank Ref Number')
    remarks = models.TextField(null=True, blank=True)
    status = models.PositiveSmallIntegerField(choices=REQUEST_STATUS, default=1)
    dt = models.DateTimeField(auto_now_add=True)

    def get_update_url(self):
        return reverse_lazy('trans:update_request', kwargs={'pk': self.pk})
Пример #26
0
print("Now I will count the eggs:")
# 鸡蛋有7个
print("Eggs", 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print("Is it true that 3+2<5-7?")
print("Is it true that 3+2<5-7?", 3 + 2 < 5 - 7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
# 哦,这就是为什么它是假的。
print("Oh, that's why it's False.")
# 再来点
print("How about some more.")
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)

# Study Drills
print(float(3 + 2 + 1 - 5 + 4 % 3 - 1 / 4 + 6))
print(float(10 / 3))

# 十六进制整数41
print(float(0x41))
# 八进制整数41
print(float(0o41))
# 二进制整数1101
print(float(0b1101))
# 保留20位小数
print('%.20f' % (4 / 3))
# 保留4位小数
from decimal import Decimal as dc
print(dc('5.026').quantize(dc('0.0000')))
Пример #27
0
print 'oct(997), hex(997) :', (oct(997), hex(997))
print "int('0100'), int('0100', 8), int('0x40', 16) :", (int('0100'), int('0100', 8), int('0x40', 16))
print '997 /  19 =', 997 / 19
print '997 %  19 =', 997 % 19
print '997 // 19 =', 997 // 19
print

# math 模块
print '【math 模块】'
import math
print 'math.pi =', math.pi
print 'math.e =', math.e
print 'math.sin(math.pi / 6) =', math.sin(math.pi / 6)
print 'mmath.sqrt(2) =', math.sqrt(2)
print

# random 模块
print '【random 模块】'
import random
print "random.random() =", random.random()
print "random.randint(1, 10) =", random.randint(1, 10)
print "random.randint(1, 10) =", random.choice(['LiXue', 'ChangXingYe', 'XueJiaJia', 'GuoNa'])
print

# 小数数字
print '【小数数字】'
print '    0.1   +     0.1   +     0.1   -     0.3   =', 0.1 + 0.1 + 0.1 - 0.3
from decimal import Decimal as dc
print "dc('0.1') + dc('0.1') + dc('0.1') - dc('0.3') =", dc('0.1') + dc('0.1') + dc('0.1') - dc('0.3')
print
Пример #28
0
    def _run_transient(self, t):
        """r
        Performs a transient simulation according to the specified settings
        updating 'b' and calling '_t_run_reactive' at each time step.
        Stops after reaching the end time 't_final' or after achieving the
        specified tolerance 't_tolerance'. Stores the initial and steady-state
        (if obtained) fields in addition to transient data (according to the
        specified 't_output').

        Parameters
        ----------
        t : scalar
            The time to start the simulation from.

        Notes
        -----
        Transient solutions are stored on the object under
        ``pore.quantity_timeStepIndex`` where *quantity* is specified in the
        ``settings`` attribute. Initial field is stored as
        ``pore.quantity_initial``. Steady-state solution (if reached) is stored
        as ``pore.quantity_steady``. Current solution is stored as
        ``pore.quantity``.
        """
        tf = self.settings['t_final']
        dt = self.settings['t_step']
        to = self.settings['t_output']
        tol = self.settings['t_tolerance']
        t_pre = self.settings['t_precision']
        s = self.settings['t_scheme']
        res_t = 1e+06  # Initialize the residual

        if not isinstance(to, list):
            # Make sure 'tf' and 'to' are multiples of 'dt'
            tf = tf + (dt - (tf % dt)) * ((tf % dt) != 0)
            to = to + (dt - (to % dt)) * ((to % dt) != 0)
            self.settings['t_final'] = tf
            self.settings['t_output'] = to
            out = np.arange(t + to, tf, to)
        else:
            out = np.array(to)
        out = np.append(out, tf)
        out = np.unique(out)
        out = np.around(out, decimals=t_pre)

        if (s == 'steady'):  # If solver in steady mode, do one iteration
            logger.info('    Running in steady mode')
            x_old = self[self.settings['quantity']]
            self._t_run_reactive(x=x_old)
            x_new = self[self.settings['quantity']]

        else:  # Do time iterations
            # Export the initial field (t=t_initial)
            n = int(-dc(str(round(t, t_pre))).as_tuple().exponent *
                    (round(t, t_pre) != int(t)))
            t_str = (str(int(round(t, t_pre) * 10**n)) + ('e-' + str(n)) *
                     (n != 0))
            quant_init = self[self.settings['quantity']]
            self[self.settings['quantity'] + '@' + t_str] = quant_init
            for time in np.arange(t + dt, tf + dt, dt):
                if (res_t >= tol):  # Check if the steady state is reached
                    logger.info('    Current time step: ' + str(time) + ' s')
                    x_old = self[self.settings['quantity']]
                    self._t_run_reactive(x=x_old)
                    x_new = self[self.settings['quantity']]
                    # Compute the residual
                    res_t = np.sum(np.absolute(x_old**2 - x_new**2))
                    logger.info('        Residual: ' + str(res_t))
                    # Output transient solutions. Round time to ensure every
                    # value in outputs is exported.
                    if round(time, t_pre) in out:
                        n = int(
                            -dc(str(round(time, t_pre))).as_tuple().exponent *
                            (round(time, t_pre) != int(time)))
                        t_str = (str(int(round(time, t_pre) * 10**n)) +
                                 ('e-' + str(n)) * (n != 0))
                        self[self.settings['quantity'] + '@' + t_str] = x_new
                        logger.info('        Exporting time step: ' +
                                    str(time) + ' s')
                    # Update A and b and apply BCs
                    self._t_update_A()
                    self._t_update_b()
                    self._apply_BCs()
                    self._A_t = (self._A).copy()
                    self._b_t = (self._b).copy()

                else:  # Stop time iterations if residual < t_tolerance
                    # Output steady state solution
                    n = int(-dc(str(round(time, t_pre))).as_tuple().exponent *
                            (round(time, t_pre) != int(time)))
                    t_str = (str(int(round(time, t_pre) * 10**n)) +
                             ('e-' + str(n)) * (n != 0))
                    self[self.settings['quantity'] + '@' + t_str] = x_new
                    logger.info('        Exporting time step: ' + str(time) +
                                ' s')
                    break
            if (round(time, t_pre) == tf):
                logger.info('    Maximum time step reached: ' + str(time) +
                            ' s')
            else:
                logger.info('    Transient solver converged after: ' +
                            str(time) + ' s')
Пример #29
0
            #unimos la imagen original con la vista de eye bird
            img_join = np.concatenate((img, img_eb_line), axis=1)
            video_output.write(np.uint8(img_join))

            #leemos la imagen correspondiente al siguiente frame
            video_input_second = round(video_input_second + frame_rate, 2)
            video_input.set(cv2.CAP_PROP_POS_MSEC, video_input_second*1000)
            _ , img = video_input.read()

            count = count + 1
            points.clear()

        #dibujamos los bounding box de la fila correspondiente al csv
        cv2.rectangle(
            img,
            (dc(row["bl"]), dc(row["bt"])),
            (dc(row["br"]), dc(row["bb"])),
            _RECTANGLE_COLOR,
            2)

        #calculamos el centro del rectangulo para representar
        #a una persona como punto
        x = (dc(row["bl"]) + dc(row["br"]))/2
        y = (dc(row["bt"]) + dc(row["bb"]))/2

        #para este caso se aplico un relleno superior para ampliar
        #la perspectiva por lo tanto se debe de actualizar la
        #altura de los puntos
        y = y + _HEIGHt_TOP_PADDING

        points.append([x, y])