示例#1
0
def test_sympy():
    """
    Using position and velocity data from subscribing to detect_target/target_state topic, this function determines:
    - time of launch
    - time of intercept
    - azimuth and elevation angles for the projectile

    After solving the symbolic system of equations, the projectile is launched.
    :return:
    """
    # constant variables
    # velocity magnitude
    velocity_mag = 20
    # projectile pos
    proj_x = 1
    proj_y = 1
    proj_z = 0
    # gravitational acc
    g = 9.8

    # test variables
    vx = 15
    vy = 10
    vz = 5
    x = 30
    y = 15
    z = 9
    T = 10
    # declare symbols

    tau, phi, theta = symbols("tau, phi, theta", positive=True, real=True)
    # create assumptions

    global_assumptions.add(Q.positive(tau))
    global_assumptions.add(Q.real(tau))
    print global_assumptions

    eq1 = symarray("0, 0, g", 3)*(T-tau)**2/2 + symarray("vx, vy, vz", 3)*T \
        - velocity_mag*symarray("sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)", 3)*(T-tau) \
        + symarray("x - proj_x, y - proj_y, z - proj_z", 3)
    system = [eq1]
    eq_symbols = [tau, phi, theta]
    try:
        print "Started solving.."
        print nonlinsolve(system, eq_symbols)
        print "Done."
    except ValueError as ve:
        print ve
    except AttributeError as ae:
        print ae
示例#2
0
    def FindWeights(self, eqs_list=None, override=False):
        w_sol = []

        if eqs_list is None:
            eqs_list = []
            if not self.wolfs_flag:
                self.GetWolfEqs()
            if not self.typ_flag:
                self.GetTypEqs()

            eqs_list.append(self.e_expr[2] - 1)
            for _ in self.typ_eq_s:
                for __ in self.typ_eq_s[_]:
                    eqs_list.append(__)

        if len(eqs_list) != len(self.w_sym_list) and not override:
            print("Number of equations %d != Number of weights: %d; %s" %
                  (len(eqs_list), len(self.w_sym_list), self.w_sym_list))
            return []

        w_sol_tmp = nonlinsolve(eqs_list, self.w_sym_list)
        for _ in w_sol_tmp:
            for __ in _:
                w_sol.append(__)

        self.w_sol.append(w_sol)
        self.m_iso.append([0.] * (self.e_max // 2))
        return w_sol
示例#3
0
def midPointDisplacement(startPoint, endPoint, heightRatio):
    length = math.sqrt(
        math.pow(startPoint[0] - endPoint[0], 2) +
        math.pow(startPoint[1] - endPoint[1], 2))

    if (length < 11):
        _canvas.stroke(
            path.line(startPoint[0], startPoint[1], endPoint[0], endPoint[1]),
            [deco.filled([color.rgb.black])])
        return

    #calculate perpendicular midPoint
    x0 = endPoint[0] - startPoint[0]
    y0 = endPoint[1] - startPoint[1]
    x1, y1 = symbols('x1,y1', real=True)

    system = [
        x0 * x1 + y0 * y1,
        x1**2 + y1**2 - (length * heightRatio * (random() * 0.4 + 0.8)**2)
    ]

    result_set = nonlinsolve(system, [x1, y1])
    count = 0
    for r in result_set:
        if random() > 0.5 or count == 1:
            midPoint_add = r
            midPoint = ((startPoint[0] + endPoint[0]) / 2 + midPoint_add[0],
                        (startPoint[1] + endPoint[1]) / 2 + midPoint_add[1])
        count += 1

    midPointDisplacement(startPoint, midPoint, heightRatio)
    midPointDisplacement(midPoint, endPoint, heightRatio)
示例#4
0
def solve(*a):
    eqs = [parse_expr(s) for s in str(a[0]).split(',')]
    target = parse_expr(str(a[1]) + '-chi')
    eqs.append(target)
    xs = set()
    for eq in eqs:
        xs.update(eq.free_symbols)
    xs = list(xs)
    xi = xs.index(Symbol('chi'))
    sols = nonlinsolve(eqs, xs)
    sol = sols.args[0]
    a[2].value = str(sol[xi])
    return True
示例#5
0
def equation_solver_2(a, b, d):
    err = relative_error()
    a_d = d.distance(a)
    b_d = d.distance(b)

    x, y = symbols('x, y', real=True)
    f1 = pow((x - a.x), 2) + pow((y - a.y), 2) - pow(a_d, 2)
    f2 = pow((x - b.x), 2) + pow((y - b.y), 2) - pow(b_d, 2)

    try:
        result = nonlinsolve([f1, f2], [x, y])
    except Exception as e:
        return Point(-1, -1, 0)

    return result
示例#6
0
def solve(equation, vars):
    print('-' * 50)
    s = list(nonlinsolve(equation, vars))
    print('Solving for variables', str(vars))
    solutions = list(s)
    print('Amount of solutions', len(solutions))
    result = []
    for args in solutions:
        print('New solution: ')
        tmp = []
        for i, arg in enumerate(args):
            print(vars[i], '=', end='')
            pprint(arg.evalf())
            tmp.append(arg)
        print('=' * 50)
        result.append(tmp)
    return result
示例#7
0
def LineWidth():

    a, k, h = symbols('a, k, h', real=True)

    ax=3
    ay=5
    bx=1
    by=-1

    eq1 = a*(ax-k)**2 +a*(ay-h)**2 - 1
    eq2 = a*(bx-k)**2 +a*(by-h)**2 - 1
    eq3 = ax/ay*(-a*(ax-k)/(a*(ay-h)))-1

    system = [eq1,eq2,eq3]

    solution=nonlinsolve(system,[a,k,h])

    pprint(solution)
示例#8
0
def shear_spacing(b, d, h, f_u, V_u):
    # 22.5.6.1
    # Assuming lambda = 1
    if f_u > 0:
        # Compression
        V_c = 2 * (1 +
                   f_u * 1000 / 2000 / b / h) * 1.0 * sqrt(F_PRIME_C) * b * d
    else:
        # Tension
        V_c = 2 * (1 +
                   f_u * 1000 / 500 / b / h) * 1.0 * sqrt(F_PRIME_C) * b * d

    # Try #3 stirrups
    d_b = rebar.diameter[3]
    A_v = 2 * rebar.area[3]

    # Table 21.2.1
    phi = 0.75

    # Unknowns
    s = Symbol('s')
    V_s = Symbol('V_s')

    # 22.5.10.5.3
    vs_eq = Eq(V_s, A_v * F_Y * d / s)
    req_eq = Eq(V_s, V_u / phi - V_c)

    solution_set = nonlinsolve([vs_eq, req_eq], [s, V_s])

    # Check s range.
    if not solution_set.is_EmptySet:
        f_s = V_u * 1000 / phi / 2 / A_v
        # 25.2.1
        min_s = max(1, d_b, D_AGG * 4 / 3)
        max_s = min(Abs(15 * 40000 / f_s - 2.5 * C_C), Abs(12 * 40000 / f_s))
        for solution in iter(solution_set):
            if solution[0] > min_s and solution[0] < max_s:
                return solution[0]
        return max_s
示例#9
0
def check_doubly_reinforced_design(b, d, d_prime, A_s, A_s_prime, M_u):
    # Unit conversion.
    M_u = M_u * 12 * 1000

    c = Symbol('c')
    epsilon_s = Symbol('epsilon_s')
    epsilon_s_prime = Symbol('epsilon_s_prime')

    compression_strain_compatibility = Eq(EPSILON_CU / c,
                                          epsilon_s_prime / (c - d_prime))
    tension_strain_compatibility = Eq(EPSILON_CU / c, epsilon_s / (d - c))

    # Assumption 1: d_prime < beta_1*c
    # Assumption 2: epsilon_s >= epsilon_y
    force_eq = Eq(
        0.85 * F_PRIME_C * BETA_1 * c * b +
        (E_S * epsilon_s_prime - 0.85 * F_PRIME_C) * A_s_prime,  # compression
        F_Y * A_s)  # tension

    c_solution_set = nonlinsolve([
        compression_strain_compatibility, tension_strain_compatibility,
        force_eq
    ], [c, epsilon_s, epsilon_s_prime])

    # Check assumption 1 & 2.
    assumption_1 = False
    assumption_2 = False
    if not c_solution_set.is_EmptySet:
        for solution in iter(c_solution_set):
            if d_prime < BETA_1 * solution[0]:
                assumption_1 = True
            if solution[1] >= EPSILON_Y:
                assumption_2 = True
            if assumption_1 and assumption_2:
                c = solution[0]
                epsilon_s = solution[1]
                epsilon_s_prime = solution[2]
                break

    if not assumption_1 or not assumption_2:
        force_eq = Eq(
            0.85 * F_PRIME_C * BETA_1 * c * b +
            (E_S * epsilon_s_prime -
             (0.85 * F_PRIME_C if assumption_1 else 0)) * A_s_prime,
            (F_Y if assumption_2 else E_S * epsilon_s) * A_s)

        # Alternative solution.
        c_solution_set = nonlinsolve([
            compression_strain_compatibility, tension_strain_compatibility,
            force_eq
        ], [c, epsilon_s, epsilon_s_prime])

        # Check alternative assumptions.
        if not c_solution_set.is_EmptySet:
            found_solution = False
            for solution in iter(c_solution_set):
                if not assumption_1 and d_prime < BETA_1 * solution[
                        0] or solution[0] < 0:
                    continue
                if not assumption_2 and solution[1] >= EPSILON_Y:
                    continue
                c = solution[0]
                epsilon_s = solution[1]
                epsilon_s_prime = solution[2]
                found_solution = True
                break

            if not found_solution:
                # There is no possible value for c.
                return 0

    # Found c.
    # Check strength.
    phi = min(0.9, 0.65 + (epsilon_s - 0.002) * 250 / 3)
    return (M_u/phi)/\
           (0.85*F_PRIME_C*BETA_1*c*b*(d-BETA_1*c/2)
            + (E_S*epsilon_s_prime-(0.85*F_PRIME_C if assumption_1 else 0))*A_s_prime*(d-d_prime))
示例#10
0
eq1 = f0 + f1 * sp_1 + f2 * sp_1**2 + f3 * sp_1**3 + f4 * sp_1**4 + f5 * sp_1**5 - math.log(
    V1)
eq2 = f0 + f1 * sp_2 + f2 * sp_2**2 + f3 * sp_2**3 + f4 * sp_2**4 + f5 * sp_2**5 - math.log(
    V2)
eq3 = f1 + 2 * f2 * sp_1 + 3 * f3 * sp_1**2 + 4 * f4 * sp_1**3 + 5 * f5 * sp_1**4 - F1 / V1
eq4 = f1 + 2 * f2 * sp_2 + 3 * f3 * sp_2**2 + 4 * f4 * sp_2**3 + 5 * f5 * sp_2**4 - F2 / V2
eq5 = 2 * f2 + 6 * f3 * sp_1 + 12 * f4 * sp_1**2 + 20 * f5 * sp_1**3 - (
    G1 / V1) + (F1 / V1)**2
eq6 = 2 * f2 + 6 * f3 * sp_2 + 12 * f4 * sp_2**2 + 20 * f5 * sp_2**3 - (
    G2 / V2) + (F2 / V2)**2

system = [eq1, eq2, eq3, eq4, eq5, eq6]
# print(is_zero_dimensional(system))

the_solution = nonlinsolve(system, [f0, f1, f2, f3, f4, f5])
print("The full solution: ")
print(the_solution)

f0 = float(the_solution.args[0][0])
f1 = float(the_solution.args[0][1])
f2 = float(the_solution.args[0][2])
f3 = float(the_solution.args[0][3])
f4 = float(the_solution.args[0][4])
f5 = float(the_solution.args[0][5])
print("Spline function parameters:")
print("f0: ", f0)
print("f1: ", f1)
print("f2: ", f2)
print("f3: ", f3)
print("f4: ", f4)
示例#11
0
a, b, h = sp.symbols('a, b, h')
v1, u2, w1, w2 = sp.symbols('v1, u2, w1, w2')

R1 = sp.Matrix([a, h, 0]) + sp.Matrix([0, v1, w1])
R2 = sp.Matrix([b, 0, 0]) + sp.Matrix([u2, 0, w2])
R3 = sp.Matrix([0, 0, 0])

V12 = R2 - R1
V23 = R3 - R2
V31 = R1 - R3

L12 = h**2 + (b - a)**2
L23 = b**2
L31 = h**2 + a**2

EQ1 = (V12.T * V12)[0, 0] - L12
EQ2 = (V23.T * V23)[0, 0] - L23
EQ3 = (V31.T * V31)[0, 0] - L31

EQS = [EQ1, EQ2, EQ3]
var = [v1, u2, w2]
print EQ1
print EQ2
print EQ3
print

sol = nonlinsolve(EQS, var)

for s in sol:
    print s
    G = i + (N - i - 1)
    birth = ((N - i) * i * (1 - s + s * F)) / ((i * (1 - s + s * F) + (N - i) *
                                                (1 - s + s * G)) * N)
    death = ((N - i) * i * (1 - s + s * G)) / ((i * (1 - s + s * F) + (N - i) *
                                                (1 - s + s * G)) * N)
    b_i.append(birth)
    d_i.append(death)
    r_i.append(1 - death - birth)

q_string = ""

for i in range(1, N):
    q_string += "q_" + str(i) + " "

q = sp.symbols(q_string)

c = 1 - q[0] * d_i[0] - q[-1] * b_i[-1]

equ = [
    -q[0] * c + q[0] * r_i[0] + q[1] * d_i[1],
    -q[-1] * c + q[-1] * r_i[-1] + q[-2] * b_i[-2]
]

for l in range(1, N - 2):
    equ.append(-q[l] * c + q[l - 1] * b_i[l - 1] + q[l] * r_i[l] +
               q[l + 1] * d_i[l + 1])

equ.append(sum(q) - 1)
unknowns = list(q) + [a]
result = nonlinsolve(equ, unknowns)
print(result)
for i in range(1, moran.N + 1):
    q_string += "q_" + str(i) + " "

q = sp.symbols(q_string)
b_i = [1 / 4] * 3
# np.copy(moran.b_i[1:])
d_i = [1 / 4, 1 / 4, 1 / 2, 1 / 2]
# np.copy(moran.d_i)
#d_i[-1] = 0.02
r_i = [1 / 2] * 4
# np.copy(moran.r_i[1:])
#r_i[-1] = 0.98

c = 1 - q[0] * d_i[0]

equ = [
    -q[0] * c + q[0] * r_i[0] + q[1] * d_i[1],
    -q[-1] * c + q[-1] * r_i[-1] + q[-2] * b_i[-2]
]

for l in range(1, moran.N - 1):
    equ.append(-q[l] * c + q[l - 1] * b_i[l - 1] + q[l] * r_i[l] +
               q[l + 1] * d_i[l + 1])

# i_to_delete = 3

# equ.pop(i_to_delete)
# equ.append(sum(q)-1)

result = nonlinsolve(equ, q)
print(result)
示例#14
0
def test_issue_18248():
    assert nonlinsolve([x*y**3-sqrt(2)/3, x*y**6-4/(9*(sqrt(3)))],x,y) == \
            FiniteSet((sqrt(3)/2, sqrt(6)/3), (sqrt(3)/2, -sqrt(6)/6 - sqrt(2)*I/2),
            (sqrt(3)/2, -sqrt(6)/6 + sqrt(2)*I/2))
示例#15
0
文件: q2_alt.py 项目: pkage/aoc-2020
            continue
        print('cos( (2 * pi * (t + {})) / {}) - 1'.format(i, int(bus)))
        eqs += cos((2 * pi * (t + i)) / int(bus))
        offset += 1
    return t, eqs - offset, offset


t, eqs, offset = create_correctbutshitty_eqs(buses)
print(eqs)


def eulers_eqs(buses):
    eqs = []
    offset = 0

    for i, bus in enumerate(buses):
        if bus == 'x':
            continue

        eqs.append()


print('... solving ...')
soln_set = nonlinsolve([eqs], [t])
soln = list(soln_set)[0][0]
print(soln)
print('evaling over set')

dom = Interval(0, 1000000000000000)
print(soln.intersect(dom))
示例#16
0
def eq_points(system, state_var):
    [eq1, eq2] = nonlinsolve(system, state_var)
    eq_pts = [eq1, eq2]
    return eq_pts
示例#17
0
def doubly_reinforced_area(b, d, d_prime, M_u):
    # Unit conversion.
    M_u *= 12 * 1000  # kip-ft to lb-in

    A_s = Symbol('A_s')
    A_s_prime = Symbol('A_s_prime')
    c = Symbol('c')
    epsilon_s = 0.005  # Find A_s and A_s_prime when epsilon_s is 0.005.
    epsilon_s_prime = Symbol('epsilon_s_prime')

    compression_strain_compatibility = Eq(EPSILON_CU / c,
                                          epsilon_s_prime / (c - d_prime))
    tension_strain_compatibility = Eq(EPSILON_CU / c, epsilon_s / (d - c))

    # Assumption 1: d_prime < beta_1*c
    force_eq = Eq(
        0.85 * F_PRIME_C * BETA_1 * c * b +
        (E_S * epsilon_s_prime - 0.85 * F_PRIME_C) * A_s_prime,  # compression
        F_Y * A_s)  # tension
    strength_eq = Eq(
        0.85 * F_PRIME_C * BETA_1 * c * b *
        (d - BETA_1 * c / 2)  # concrete compression
        + (E_S * epsilon_s_prime - 0.85 * F_PRIME_C) * A_s_prime *
        (d - d_prime),  # reinforcement compression
        M_u / 0.9)  # required strength

    # Solve.
    solution_set = nonlinsolve([
        compression_strain_compatibility, tension_strain_compatibility,
        force_eq, strength_eq
    ], [A_s, A_s_prime, c, epsilon_s_prime])

    if not solution_set.is_EmptySet:
        # Check assumption 1.
        for solution in iter(solution_set):
            if d_prime < BETA_1 * solution[2]:
                return solution[0], solution[1]

    # Assumption disagreement.
    # Change assumption.
    # Assumption 1: d_prime >= beta_1*c
    force_eq = Eq(
        0.85 * F_PRIME_C * BETA_1 * c * b +
        E_S * epsilon_s_prime * A_s_prime,  # compression
        F_Y * A_s)  # tension
    strength_eq = Eq(
        0.85 * F_PRIME_C * BETA_1 * c * b *
        (d - BETA_1 * c / 2)  # concrete compression
        + E_S * epsilon_s_prime * A_s_prime *
        (d - d_prime),  # reinforcement compression
        M_u / 0.9)  # required strength

    # Solve.
    solution_set = nonlinsolve([
        compression_strain_compatibility, tension_strain_compatibility,
        force_eq, strength_eq
    ], [A_s, A_s_prime, c, epsilon_s_prime])

    if not solution_set.is_EmptySet:
        # Check assumption 1.
        for solution in iter(solution_set):
            if d_prime >= BETA_1 * solution[2] and solution[2] > 0:
                return solution[0], solution[1]

    # No solution.
    return nan, nan
示例#18
0
#!/usr/bin/env python

# Prerequisites: have sympy installed (or use Anaconda)
import sympy

# from math import tan
from sympy.solvers.solveset import nonlinsolve
from sympy.core.symbol import symbols
from sympy import tan, pprint

x1, y1, doa_1, theta_1 = symbols('x1, y1, doa1, theta1', real=True)
x2, y2, doa_2, theta_2 = symbols('x2, y2, doa2, theta2', real=True)
x3, y3, doa_3, theta_3 = symbols('x3, y3, doa3, theta3', real=True)
xr, yr, theta_r = symbols('xr, yr, theta_r', real=True)

# eq1 = doa_1 + theta_r - theta_1 # theta 1 = theta_r + doa_1
# eq2 = doa_2 + theta_r - theta_2 # theta 2 = theta_r + doa_2
# eq3 = doa_3 + theta_r - theta_3 # theta 3 = theta_r + doa_3
# eq4 = (y1 - yr) / (x1 - xr) - tan(theta_1)
# eq5 = (y2 - yr) / (x2 - xr) - tan(theta_2)
# eq6 = (y3 - yr) / (x3 - xr) - tan(theta_3)

eq1 = (y1 - yr) / (x1 - xr) - tan(doa_1 + theta_r)
eq2 = (y2 - yr) / (x2 - xr) - tan(doa_2 + theta_r)
eq3 = (y3 - yr) / (x3 - xr) - tan(doa_3 + theta_r)

result = nonlinsolve([eq1, eq2, eq3], [xr, yr, theta_r])

pprint(result, use_unicode=True)
示例#19
0
plt.ylabel('Acceleration Magnitude',fontsize=25)
plt.title('Numerical Differentiation Method',fontsize=30)
plt.show()
#============================ Q3 ==========================
print('\nNow entering Q3...\n') 
print('Part A:')
# evalute the velocity at t = 1 and convert it to numpy float
v_x = np.array((sp.exp(-t/T1)).diff(t).subs(t,1.0)).astype(np.float64)
v_y = np.array((2*sp.cos(t/T2)).diff(t).subs(t,1.0)).astype(np.float64)
# calculate the magnitude of the velocity
v = np.sqrt(np.add(np.square(v_x),np.square(v_y)))
print(f'The magnitude velocity of the particle at time = 1s is:{v} m/s\n')

print('Part B:')
# solve the nonlinear function of the r_y = 0 with the variable t
t_sol = nonlinsolve([r_y],[t])
# pretty print the solutions as sets
print('The time t when ry = 0 are:')
pprint(t_sol)
#============================ Q4 ==========================
print('\nNow entering Q4...')
print('Animating the trajectory of the particle...')
# 100 frames
frame_num = 100
# 50ms per frame
interval = 50
t = np.linspace(0,frame_num)
# claim the numpy function of position
x = np.exp(-t/T1)
y = 2*np.cos(t/T2)
# create the figure
示例#20
0
def previa_intersecçao(identif_inicial, identif_final):
    """
    Uma *mini simulação de Epsi*. Para poucos nós em cada direção será checado se os limites são coerentes ou não, 
    ou seja, **se as funções convergiram para o determinado espaçamento de nós ou não**.
    
    Args:
        identif_inicial (:obj:`str`): Determine o início do intervalo de superfícies a serem calculadas através da identificação :obj:`identif`.
        identif_final (:obj:`str`): Determine o final do intervalo (endpoint não incluido) de superfícies a serem calcuadas através da identificação :obj:`identif`.
        
    Note:
        Como dito anteriormente, é recomendado fugir de superfícies mais complexas com graus (ou então numero de pontos em cada direção :obj:`[u,v]`) 
        elevados e/ou com muitas variações em mais de duas direções :obj:`xyz`. Para enfatizar esse argumento, podemos trazer alguns números: imagine uma 
        primeira superfície de 1ª ordem (2 pontos em cada direção) com variações constantes/lineares em todas direções (um quadrado ou retângulo). Agora, 
        como segunda superfície, imagine outra superfície de 1ª ordem com variações não-constantes/não-lineares em todas direções, uma superfície mais 
        alta de um lado do que de outro, ao mesmo tempo que é mais larga em um lado do que em outro e que esteja sendo 'torcida'. O cálculo de limites 
        da Epsi da primeira demora cerca de **25%** do tempo quando comparada à segunda superfície, mesmo ambas tendo o mesmo grau. No primeiro caso, 
        das 3 equações, apenas 2 dependerão de apenas 1 variável e a outra será uma constante. No segundo caso, todas as 3 equações dependem de 2 variáveis, 
        o que se torna bastante custoso.
        Porém, caso não seja possível fugir destas complicações, na hora de plotar sua superfície, chame esta função para verificar se os vetores de cada
        plano estão reconhecendo a sua superfície como deveriam.
    
    """

    fig = plt.figure(figsize=(9, 9))
    ax = fig.add_subplot(1, 1, 1, projection='3d', proj_type='ortho')

    ax.set_xlabel('x'), ax.set_ylabel('y'), ax.set_zlabel('z'), ax.set_xlim(
        0,
        max([lx, ly,
             lz])), ax.set_ylim(0,
                                max([lx, ly,
                                     lz])), ax.set_zlim(0, max([lx, ly, lz])),
    ax.view_init(25, -145), (), ax.set_title('Superfície/Intersecções',
                                             size=20)

    for plot in np.arange(identif_inicial, identif_final, 1):
        ax.plot_surface(armz_eq[f'x{plot}'][3],
                        armz_eq[f'y{plot}'][3],
                        armz_eq[f'z{plot}'][3],
                        color='c',
                        antialiased=True,
                        shade=True,
                        alpha=0.4)  #cmap='Wistia'

        for n1, n2, d1, d2, e1, e2, cor in [
                nz_visualizacao, ny_visualizacao, dz_visualizacao,
                dy_visualizacao, f'z{plot}', f'y{plot}', 'magenta'
        ], [
                nx_visualizacao, ny_visualizacao, dx_visualizacao,
                dy_visualizacao, f'x{plot}', f'y{plot}', 'blue'
        ], [
                nx_visualizacao, nz_visualizacao, dx_visualizacao,
                dz_visualizacao, f'x{plot}', f'z{plot}', 'aqua'
        ]:
            nobj = 0
            for c1 in range(0, n1, 1):
                for c2 in range(0, n2, 1):
                    try:
                        sol = nonlinsolve([
                            armz_eq[e1][1][0] - c1 * d1,
                            armz_eq[e2][1][0] - c2 * d2
                        ], [u, v])
                        for a in range(0, len(sol.args)):
                            if sol.args[a][0].is_real == True:
                                if 0 <= sol.args[a][0] <= 1:
                                    if sol.args[a][1].is_real == True:
                                        if 0 <= sol.args[a][1] <= 1:
                                            nobj += 1
                                            ax.scatter(
                                                armz_eq[f'x{plot}'][2](
                                                    float(sol.args[a][0]),
                                                    float(sol.args[a][1])),
                                                armz_eq[f'y{plot}'][2](
                                                    float(sol.args[a][0]),
                                                    float(sol.args[a][1])),
                                                armz_eq[f'z{plot}'][2](
                                                    float(sol.args[a][0]),
                                                    float(sol.args[a][1])),
                                                s=100,
                                                color=cor)
                    except:
                        pass

            for cx in range(0, nx_visualizacao, 1):
                for cy in range(0, ny_visualizacao, 1):
                    ax.plot((cx * dx_visualizacao, cx * dx_visualizacao),
                            (cy * dy_visualizacao, cy * dy_visualizacao),
                            (0, lz),
                            color='blue',
                            linestyle='--',
                            linewidth=1.2)

            for cx in range(0, nx_visualizacao, 1):
                for cz in range(0, nz_visualizacao, 1):
                    ax.plot((cx * dx_visualizacao, cx * dx_visualizacao),
                            (0, ly),
                            (cz * dz_visualizacao, cz * dz_visualizacao),
                            color='aqua',
                            linestyle='--',
                            linewidth=1.2)

            for cy in range(0, ny_visualizacao, 1):
                for cz in range(0, nz_visualizacao, 1):
                    ax.plot((0, lx),
                            (cy * dy_visualizacao, cy * dy_visualizacao),
                            (cz * dz_visualizacao, cz * dz_visualizacao),
                            color='magenta',
                            linestyle='--',
                            linewidth=1.2)

            if nobj > 0:
                print(
                    f'Objeto #{plot}: plano {str(e1[0]+e2[0])} encontra {nobj} intersecçoes',
                    '\n')
            else:
                print(
                    f'Objeto #{plot}: plano {str(e1[0]+e2[0])} não encontra intersecçoes ou não convergiu',
                    '\n')
示例#21
0
def gen_epsi(tipo, plano, identif, simetria='global', raf0='normal'):
    """
    O ponto crítico do código.
    
    Aqui, usamos as equações geradas pelos pontos fornecidos pelo usuário para setar os limites de onde é sólido (na Epsi, :obj:`1`) e onde
    não é sólido (na Epsi, :obj:`0`). Vamos setar o que é considerado entrada e saída, ou ambos ao mesmo tempo, **para todas as superfícies criadas**. 
    Vamos, também, tornar mais barata o cálculo de nossa Epsi com simetrias. Vamos definir qual o melhor plano para calcular os limites.
    
    Warning:
        **Preste atenção. Se algo pode dar errado, é aqui.**
        
    Args:
        tipo (:obj:`str`): Defina se a superfície em questão é considerada uma entrada, uma saída ou ambos em relação ao sólido.
        
            +-------------------------+------------------------------------+------------+
            | Tipo                    | Variável                           | Exemplo    |
            +=========================+====================================+============+
            | Entrada                 | :obj:`'entrada+saída e/ou entrada'`| /          |
            +-------------------------+------------------------------------+------------+
            | Saída                   | :obj:`'entrada+saída e/ou saída'`  | /          |
            +-------------------------+------------------------------------+------------+
            | Entrada/Saída Pura      | Both                               | U, V       |
            +-------------------------+------------------------------------+------------+
            | Entrada/Saída + Entrada | :obj:`'entrada+saída e/ou entrada'`| J          |
            +-------------------------+------------------------------------+------------+
            | Entrada/Saída + Saída   | :obj:`'entrada+saída e/ou saída'`  | J (inverse)| 
            +-------------------------+------------------------------------+------------+
        
    Note:
        Caso seja a superfície identificada com :obj:`identif` seja *entrada*, a partir do momento em que a Epsi encontrar a superfície até o fim da 
        Epsi será setado como 1. Caso seja *saída*, 
        a partir do momento em que a Epsi encontrar a superfície até o fim da Epsi será setado como 0. *É necessário perceber que a ordem com que essa 
        função é chamada tem muita importância:* caso o usuário chame primeiro as saídas, o código vai entender que a partir do encontro da superfície 
        é necessário marcar como 0 algo que já está setado como 0 (a matriz Epsi é setada inicialmente apemas com 0, com dimensões nx, ny e nz). Seguindo a lógica, 
        o usuário agora então chamaria as entradas. A partir do encontro da superfície, tudo será setado com 1 até o fim da matriz e assim ficará definido. 
        Ou seja, o sólido *não foi representado corretamente.*
    
    Warning:
        Caso construída uma superfície que possua segmentos com possíveis entradas/saídas (um U ou um 0), certificar que a superfície seja construída 
        no sentido positivo: os pontos iniciais devem ser mais próximos da origem do que os pontos finais, independente do plano.

    Args: 
        plano (:obj:`str`): Escolha o melhor plano para resolver sua superfície. Caso o plano xy seja o melhor, setar :obj:`plano='xy'`. Pode assumir apenas :obj:`'xz','xy','zy'`.
        
    Note:
        **Mas, como assim 'plano'?**\
        Para cada combinação de coordenada (xy, xz ou zy), imagine um vetor saíndo de cada nó existente.
        Como por exemplo, falaremos do plano xy. De cada posição x e de cada posição y possível, sairá um vetor em direção à z.
        Toda vez que esse vetor cruzar uma superfície, será contabilizado um limite para a Epsi. O usuário já determinou que 
        tipo de limite será no argumento anterior.
        *Logo, é de extrema importância que o usuário escolha o plano certo para resolver o seu sólido.*
        Imagine outro exemplo, onde o usuário construiu um quadrado no plano xy (ou seja, paralelo ao plano xy), com alguma altura constante qualquer.
        Esse quadrado não possui dimensão alguma para qualquer plano a não ser o plano xy.
        Em outras palavras, o plano zy e o plano zx nunca cruzarão este quadrado, logo a Epsi não será construída corretamente pois não haverá limite algum para isso.
        E isso é perfeitamente demonstrado pela :obj:`previa_intersecçao`. Inclusive, o retorno desta função explicita onde há interceptação dos vetores com a superfície, 
        tornando mais clara a escolha deste argumento.
        
        **Dica:** normalmente o plano com mais intersecções na :obj:`previa_intersecçao` é o mais correto a ser escolhido.
    
    Args:
        identif(:obj:`str`): Chame a superfície já determinada e identificada com :obj:`identif`.
        simetria(:obj:`str`, optional): Defina alguma simetria de auxílio para barateamento do cálculo da Epsi. Pode assumir :obj:`'simetria_x','simetria_y',simetria_z'`.
        
    Warning:
        Caso utilize a simetria, projete apenas metade das superfícies caso elas cruzem o eixo de simetria. Caso contrário, o método não resulta em ganhos significativos. 

    Args:
       raf0(:obj:`str`, optional): Não há necessidade alguma de manipulação por parte do usuário. 
    """
    dx_gen, dy_gen, dz_gen = dx, dy, dz
    nx_gen, ny_gen, nz_gen = nx, ny, nz
    matrix_gen = epsi_3d

    try:
        if raf0 == 'x':
            dx_gen, nx_gen = dx_raf, nx_raf
            matrix_gen = epsi_3d_x_raf
        if raf0 == 'y':
            dy_gen, ny_gen = dy_raf, ny_raf
            matrix_gen = epsi_3d_y_raf
        if raf0 == 'z':
            dz_gen, nz_gen = dz_raf, nz_raf
            matrix_gen = epsi_3d_z_raf
    except:
        pass

    max_z, max_y, max_x = 0, 0, 0

    for p, k in armz_eq.items():
        if p[0] == 'z':
            if k[5] > max_z:
                max_z = k[5]
        if p[0] == 'y':
            if k[5] > max_y:
                max_y = k[5]
        if p[0] == 'x':
            if k[5] > max_x:
                max_x = k[5]

    max_x, max_y, max_z = int(max_x / dx_gen), int(max_y / dy_gen), int(max_z /
                                                                        dz_gen)

    if plano == 'zy':
        eixo1, min_1, max_1, d1 = str(f'z{identif}'), math.ceil(
            armz_eq[f'z{identif}'][4] / dz_gen), int(
                armz_eq[f'z{identif}'][5] / dz_gen), dz_gen
        eixo2, min_2, max_2, d2 = str(f'y{identif}'), math.ceil(
            armz_eq[f'y{identif}'][4] / dy_gen), int(
                armz_eq[f'y{identif}'][5] / dy_gen), dy_gen
        eixo3, min_3, max_3, d3 = str(f'x{identif}'), math.ceil(
            armz_eq[f'x{identif}'][4] / dx_gen), max_x, dx_gen

    if plano == 'xz':
        eixo1, min_1, max_1, d1 = str(f'x{identif}'), math.ceil(
            armz_eq[f'x{identif}'][4] / dx_gen), int(
                armz_eq[f'x{identif}'][5] / dx_gen), dx_gen
        eixo2, min_2, max_2, d2 = str(f'z{identif}'), math.ceil(
            armz_eq[f'z{identif}'][4] / dz_gen), int(
                armz_eq[f'z{identif}'][5] / dz_gen), dz_gen
        eixo3, min_3, max_3, d3 = str(f'y{identif}'), math.ceil(
            armz_eq[f'y{identif}'][4] / dy_gen), max_y, dy_gen

    if plano == 'xy':
        eixo1, min_1, max_1, d1 = str(f'x{identif}'), math.ceil(
            armz_eq[f'x{identif}'][4] / dx_gen), int(
                armz_eq[f'x{identif}'][5] / dx_gen), dx_gen
        eixo2, min_2, max_2, d2 = str(f'y{identif}'), math.ceil(
            armz_eq[f'y{identif}'][4] / dy_gen), int(
                armz_eq[f'y{identif}'][5] / dy_gen), dy_gen
        eixo3, min_3, max_3, d3 = str(f'z{identif}'), math.ceil(
            armz_eq[f'z{identif}'][4] / dz_gen), max_z, dz_gen

    grau = max(armz_eq[f'z{identif}'][6], armz_eq[f'z{identif}'][7])

    bar = progressbar.ProgressBar(widgets=[
        f'#{identif} ({(max_2+1-min_2)*(max_1+1-min_1)} knot², order {grau}): ',
        progressbar.AnimatedMarker(),
        progressbar.Percentage(),
        progressbar.Bar(),
        '  ',
        progressbar.Timer(),
    ],
                                  max_value=(max_1 + 1 - min_1) *
                                  (max_2 + 1 - min_2)).start()

    for c1 in range(min_1, max_1 + 1, 1):
        for c2 in range(min_2, max_2 + 1, 1):
            bar += 1
            try:
                lista_args = []
                intersec = nonlinsolve([
                    armz_eq[f'{eixo1}'][1][0] - c1 * d1,
                    armz_eq[f'{eixo2}'][1][0] - c2 * d2
                ], [u, v])
                for prmt in range(0, len(intersec.args)):
                    if intersec.args[prmt][0].is_real == True and 0 <= round(
                            intersec.args[prmt][0], 5) <= 1:
                        if intersec.args[prmt][
                                1].is_real == True and 0 <= round(
                                    intersec.args[prmt][1], 5) <= 1:
                            lista_args += intersec.args[prmt]

                for c3 in range(min_3, max_3 + 1, 1):
                    if tipo == 'entrada+saída e/ou saída':
                        if len(lista_args) == 4:
                            if armz_eq[f'{eixo3}'][2](
                                    lista_args[0], lista_args[1]
                            ) <= c3 * d3 < armz_eq[f'{eixo3}'][2](
                                    lista_args[2], lista_args[3]):
                                if plano == 'zy':
                                    matrix_gen[c3][c2][c1] = 1
                                if plano == 'xz':
                                    matrix_gen[c1][c3][c2] = 1
                                if plano == 'xy':
                                    matrix_gen[c1][c2][c3] = 1
                        if len(lista_args) == 2:
                            if c3 * d3 > armz_eq[f'{eixo3}'][2](lista_args[0],
                                                                lista_args[1]):
                                if plano == 'zy':
                                    matrix_gen[c3][c2][c1] = 0
                                if plano == 'xz':
                                    matrix_gen[c1][c3][c2] = 0
                                if plano == 'xy':
                                    matrix_gen[c1][c2][c3] = 0

                    if tipo == 'entrada+saída e/ou entrada':
                        if len(lista_args) == 4:
                            if armz_eq[f'{eixo3}'][2](
                                    lista_args[0], lista_args[1]
                            ) <= c3 * d3 < armz_eq[f'{eixo3}'][2](
                                    lista_args[2], lista_args[3]):
                                if plano == 'zy':
                                    matrix_gen[c3][c2][c1] = 1
                                if plano == 'xz':
                                    matrix_gen[c1][c3][c2] = 1
                                if plano == 'xy':
                                    matrix_gen[c1][c2][c3] = 1
                        if len(lista_args) == 2:
                            if c3 * d3 >= armz_eq[f'{eixo3}'][2](
                                    lista_args[0], lista_args[1]):
                                if plano == 'zy':
                                    matrix_gen[c3][c2][c1] = 1
                                if plano == 'xz':
                                    matrix_gen[c1][c3][c2] = 1
                                if plano == 'xy':
                                    matrix_gen[c1][c2][c3] = 1

            except:
                pass

    if simetria == 'simetria_y':
        if (ny_gen % 2 != 0) == True:  #impar
            lado_zerado = int(ny_gen / 2)
            lado_calculado = int(ny_gen / 2)
            for cy in range(int(ny_gen / 2), ny_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[:, lado_zerado, :] = matrix_gen[:,
                                                           lado_calculado, :]

        if (ny_gen % 2 != 0) == False:  #par
            lado_zerado = int(ny_gen / 2 - 1)
            lado_calculado = int(ny_gen / 2)
            for cy in range(int(ny_gen / 2) - 1, ny_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[:, lado_zerado, :] = matrix_gen[:,
                                                           lado_calculado, :]

    if simetria == 'simetria_x':
        if (nx_gen % 2 != 0) == True:
            lado_zerado = int(nx_gen / 2)
            lado_calculado = int(nx_gen / 2)
            for cx in range(int(nx_gen / 2), nx_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[lado_zerado, :, :] = matrix_gen[
                    lado_calculado, :, :]

        if (nx_gen % 2 != 0) == False:
            lado_zerado = int(nx_gen / 2 - 1)
            lado_calculado = int(nx_gen / 2)
            for cx in range(int(nx_gen / 2) - 1, nx_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[lado_zerado, :, :] = matrix_gen[
                    lado_calculado, :, :]

    if simetria == 'simetria_z':
        if (nz_gen % 2 != 0) == True:
            lado_zerado = int(nz_gen / 2)
            lado_calculado = int(nz_gen / 2)
            for cz in range(int(nz_gen / 2), nz_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[:, :, lado_zerado] = matrix_gen[:, :,
                                                           lado_calculado]

        if (nz_gen % 2 != 0) == False:
            lado_zerado = int(nz_gen / 2 - 1)
            lado_calculado = int(nz_gen / 2)
            for cz in range(int(nz_gen / 2) - 1, nz_gen - 1):
                lado_zerado += 1
                lado_calculado -= 1
                matrix_gen[:, :, lado_zerado] = matrix_gen[:, :,
                                                           lado_calculado]

    armz_nomenclt_epsi[f'{identif}'] = (tipo, plano, identif, simetria)

    bar.finish()