Пример #1
0
def get_places():
    cur_path = os.getcwd()
    path = cur_path[:-7] + "Data/"
    os.chdir(path)
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    query = "SELECT * FROM places"
    for line in c.execute(query):
        line = list(line[1:5])
        if len(places) == 0:
            line.append(0)
        else:
            line.append(get_distance(line, places[0]))
            places.append(line)

    for u in range(0, 182):
        user = get_folder(u)
        query = "SELECT * FROM master" + user
        lines = []
        now = time.time()
        for line in c.execute(query):
            line = list(line[1:])
            if len(places) == 0:
                line.append(0)
            else:
                line.append(get_distance(line, places[0]))
            lines.append(line)
        for line in lines:
            if line not in places:
                if not find_place(places, line):
                    if line[4] == 0 and len(places) != 0:
                        line[4] = get_distance(line, places[0])
                    places.append(line)
                    # print(line)
            if time.time() - now > 60:
                print("Processing user: "******"Line: ", line)
                now = time.time()
        print("User: "******"Num Places: ", len(places))
        print("Num Lines", len(lines))

        places.sort(key=lambda place: place[4])

        query = "DELETE FROM places"
        c.execute(query)
        query = "DELETE FROM sqlite_sequence WHERE NAME = 'places'"
        c.execute(query)

        for place in places:
            c.execute(
                "INSERT INTO places(latitude, longitude, dated, timed) VALUES \
                (?, ?, ?, ?)", place[0:4])
        print 'Entered', user
        conn.commit()
    conn.close()
    os.chdir(cur_path)
Пример #2
0
    def find_figures(planes):
        warnings.filterwarnings('error')

        figures = []

        # Находим фигуры
        for i in range(planes.shape[0]):
            plane = planes[i]
            a = plane[:3]
            b = plane[3:6]
            c = plane[6:9]
            material_id = plane[-1]

            # Определяем длинны сторон трехугольника
            ab = get_distance(a, b)
            bc = get_distance(b, c)
            ac = get_distance(a, c)

            znam = 4 * (ab + bc + ac)

            # Исключаем деление на 0
            if bc == 0 or ac == 0 or znam == 0:
                continue

            # Находим радиус вписанной окружности
            try:
                r = (((-ab + bc + ac) * (ab - bc + ac) * (ab + bc - ac)) /
                     znam)**0.5
            except Warning:
                continue
            # Отсекаем фигуры в ходе вычисления которых возникла ошибка связанная с плавующей запятой
            # и фигуры радиус которых равен 0
            # if np.isnan(r) or r == 0:
            #     continue

            # Находим соотношение АВ/ВС
            l1 = ab / bc

            # Находим координаты точки М
            m = np.empty(3)
            for i in range(3):
                m[i] = (a[i] + l1 * c[i]) / (1 + l1)

            # Точка пересечения биссектрис (инцентр) делит биссектрису ВМ по соотношению:
            l2 = (ab + bc) / ac

            # Находим координаты точки О (центр вписанной окружности)
            o = np.empty(3)
            for i in range(3):
                o[i] = (b[i] + l2 * m[i]) / (1 + l2)

            # Записываем:
            # -	три координаты геометрического центра (Ox, Oy, Oz)
            # -	длина действующего радиуса (R)
            # -	код материала
            figures.append([o[0], o[1], o[2], r, material_id])

        return figures
Пример #3
0
def get_places():
    cur_path = os.getcwd()
    path = cur_path[:-7] + "Data/"
    os.chdir(path)
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    query = "SELECT * FROM places"
    for line in c.execute(query):
        line = list(line[1:5])
        if len(places) == 0:
            line.append(0)
        else:
            line.append(get_distance(line, places[0]))
            places.append(line)

    for u in range(0, 182):
        user = get_folder(u)
        query = "SELECT * FROM master" + user
        lines = []
        now = time.time()
        for line in c.execute(query):
            line = list(line[1:])
            if len(places) == 0:
                line.append(0)
            else:
                line.append(get_distance(line, places[0]))
            lines.append(line)
        for line in lines:
            if line not in places:
                if not find_place(places, line):
                    if line[4] == 0 and len(places) != 0:
                        line[4] = get_distance(line, places[0])
                    places.append(line)
                    # print(line)
            if time.time() - now > 60:
                print("Processing user: "******"Line: ", line)
                now = time.time()
        print("User: "******"Num Places: ", len(places))
        print("Num Lines", len(lines))

        places.sort(key=lambda place: place[4])

        query = "DELETE FROM places"
        c.execute(query)
        query = "DELETE FROM sqlite_sequence WHERE NAME = 'places'"
        c.execute(query)

        for place in places:
            c.execute("INSERT INTO places(latitude, longitude, dated, timed) VALUES \
                (?, ?, ?, ?)", place[0:4])
        print 'Entered',user
        conn.commit()
    conn.close()
    os.chdir(cur_path)
Пример #4
0
def calc_distances_residues(chain1, chain2):
    """Function to calculate distances between CA. Returns a tuple with: min, max, number of atoms and a counter of
    distances under 8A."""
    import functions
    chain1_redef = copy.copy(functions.adapt_chain(chain1))
    chain2_redef = copy.copy(functions.adapt_chain(chain2))
    at1 = chain1_redef.get_atoms()
    at2 = chain2_redef.get_atoms()
    list1 = []
    list2 = []
    arr = []

    for atom1 in at1:
        if atom1.id == 'CA':
            list1.append(atom1)
    for atom2 in at2:
        if atom2.id == 'CA':
            list2.append(atom2)

    for combination in itertools.product(list1, list2):
        coords1 = combination[0].get_coord()
        coords2 = combination[1].get_coord()
        dist = functions.get_distance(list(coords1.tolist()),
                                      list(coords2.tolist()))
        arr.append(dist)

    num_min = 0
    if len(arr) != 0:
        nparr = numpy.array(arr)
        for dist in nparr:
            if dist < 8:
                num_min += 1

        dist_tuple = (min(abs(nparr)), max(abs(nparr)), len(nparr), num_min)
        return dist_tuple
Пример #5
0
def find_place_linear(places, p):
    for i in range(len(places)):
        distance = get_distance(places[i][1:3], p[1:3])
        if distance <= 15:
            return i

    return -1
Пример #6
0
def find_place_linear(places, p):
    for i in range(len(places)):
        distance = get_distance(places[i][1:3], p[1:3])
        if distance <= 15:
            return i

    return -1
Пример #7
0
 def get_distance(points):
     """
     :param points: часть провода для которого вы должны вычислить расстояние
     :return: длина части провода
     """
     res = 0
     for i in range(len(points) - 1):
         res += get_distance(points[i], points[i + 1])
     return res
Пример #8
0
def find_place(places, line):
    '''
    :param places:
    :param line:
    :return: Return true if the the distance between the coordinates is within 5 meters from any coordinate in places
    '''
    if len(places) == 0:
        return False
    low = 0
    high = len(places)
    while low <= high:
        mid = int((low + high)/2)
        if get_distance(places[mid], line) <= 5:
            return False
        else:
            high = mid - 1
    return True
Пример #9
0
def test_places():
    cur_path = change_path_to_data()
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    distances = []
    query = "SELECT * FROM places"
    for line in c.execute(query):
        places.append(line[1:5])
    for place in places:
        distance = get_distance(place, places[0])
        distances.append(distance)
    if all(distances[i] <= distances[i+1] for i in range(len(distances)-1)):
        print("Its sorted :D")
    else:
        print("Not sorted.")
    back_to_path(cur_path)
Пример #10
0
def find_place(places, line):
    '''
    :param places:
    :param line:
    :return: Return true if the the distance between the coordinates is within 5 meters from any coordinate in places
    '''
    if len(places) == 0:
        return False
    low = 0
    high = len(places)
    while low <= high:
        mid = int((low + high) / 2)
        if get_distance(places[mid], line) <= 5:
            return False
        else:
            high = mid - 1
    return True
Пример #11
0
def test_places():
    cur_path = change_path_to_data()
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    distances = []
    query = "SELECT * FROM places"
    for line in c.execute(query):
        places.append(line[1:5])
    for place in places:
        distance = get_distance(place, places[0])
        distances.append(distance)
    if all(distances[i] <= distances[i + 1]
           for i in range(len(distances) - 1)):
        print("Its sorted :D")
    else:
        print("Not sorted.")
    back_to_path(cur_path)
Пример #12
0
def test_distance():
    cur_path = change_path_to_data()

    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    distances = []
    query = "SELECT * FROM master000"
    for line in c.execute(query):
        places.append(list(line))

    for place in places:
        place.append(get_distance(place[1:], places[0][1:]))

    places.sort(key=lambda place: -place[5])

    count = 0
    for place in places:
        print(str(place[0]) + ": " + str(place[5]))
        count += 1
        if count == 20:
            break

    back_to_path(cur_path)
Пример #13
0
def test_distance():
    cur_path = change_path_to_data()

    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    places = []
    distances = []
    query = "SELECT * FROM master000"
    for line in c.execute(query):
        places.append(list(line))

    for place in places:
        place.append(get_distance(place[1:], places[0][1:]))

    places.sort(key=lambda place: -place[5])

    count = 0
    for place in places:
        print(str(place[0]) + ": " + str(place[5]))
        count += 1
        if count == 20:
            break

    back_to_path(cur_path)
Пример #14
0
def get_places_by_date_time():
    cur_path = change_path_to_data()
    conn = sqlite3.connect('data.db')
    c = conn.cursor()

    new_places = []

    for u in range(0, 10):
        user = get_folder(u)

        # Get all dates from the database
        query = "SELECT DISTINCT dated FROM master" + user      # 6367 for 000, 256 for 001
        dates = []
        for line in c.execute(query):
            dates.append(line[0])

        places = []

        # places.append([172042, 39.955832, 116.329224, '2009-07-05', '04:44:31'])
        # For each date in the database, get all the locations and extract places based on 10 minute difference
        for d in dates:
            query = "SELECT * FROM master" + user + " WHERE dated = '" + str(d) + "'"
            # print(query)
            prev = 0
            for line in c.execute(query):
                line = list(line)
                line[4] = line[4][:-1]
                if prev == 0:
                    # print(line, prev)
                    places.append(line)
                    prev += 1
                else:
                    minutes = get_minutes(places[prev-1][4], line[4])
                    # print(minutes)
                    if minutes > 15:
                        distance = get_distance(places[prev-1][1:3], line[1:3])
                        if distance > 20:
                            if line not in places:
                                # line.append(1)
                                # print(line, minutes, distance)
                                places.append(line)
                                prev += 1

        # Add entries to new_places
        initial = len(new_places)
        if len(new_places) == 0:
            for p in places:
                p.append(1)
                new_places.append(p)
        else:
            for p in places:
                index = find_place_linear(new_places, p)
                if index == -1:
                    p.append(1)
                    new_places.append(p)
                else:
                    new_places[index][5] += 1

        print("User: "******"Number of places: ", len(places))
        print("Number of places added: ", len(new_places) - initial)

    # print(new_places)
    print("Total new places: ", len(new_places))
    # Remove entries from new_places table
    query = "DELETE FROM new_places"
    c.execute(query)
    query = "DELETE FROM sqlite_sequence WHERE NAME = 'new_places'"
    c.execute(query)

    for place in new_places:
        c.execute("INSERT INTO new_places(latitude, longitude, dated, timed, weight) VALUES (?, ?, ?, ?, ?)", place[1:])
        # print(place[0:4])

    conn.commit()
    conn.close()
    back_to_path(cur_path)
Пример #15
0
    def do(self, is_bba=False):
        if is_bba:
            C = (self.b1 + self.b2) / 2
            p_GC = C - self.BBA.point
            p_b1b2 = self.b2 - self.b1
            d_GC = get_distance(self.BBA.point, C)
            d_current = get_distance(self.b1, self.b2)
            cos_alfa = get_cos(p_GC, p_b1b2, d_GC, d_current)
            sin_alfa = mt.sin(mt.acos(cos_alfa))
            r = get_distance(self.BBA.point, C)
            w = 2 * mt.pi * self.BBA_f
            er = self.BBA_E * ((1 / (w * r**3) - w / (r * ct.CC**2) + 1 /
                                (ct.CC * r**2)) /
                               (1 / w - w / ct.CC**2 + 1 / ct.CC))

            Uf = mt.copysign(d_current / 2 * er * sin_alfa, cos_alfa)

            return Uf

        # вычисление векторов фрагментов
        p_a1a2 = self.a2 - self.a1
        p_b1b2 = self.b2 - self.b1
        # вычисление длин отрезков провода (AB, BC, CD, etc.)
        d_compare = get_distance(self.a1, self.a2)
        d_current = get_distance(self.b1, self.b2)
        # вычисление длин отрезков между проводами (a1b1, a1b2, a1C2, etc.)
        d_a1b1 = get_distance(self.a1, self.b1)
        d_a2b1 = get_distance(self.a2, self.b1)
        d_a1b2 = get_distance(self.a1, self.b2)
        d_a2b2 = get_distance(self.a2, self.b2)
        # вычисляем косинус угла между отрезками
        cos_segment = get_cos(p_a1a2, p_b1b2, d_compare, d_current)

        p1x, p1y, p1z = p_a1a2
        p2x, p2y, p2z = p_b1b2

        CE = 0  # величина электрической емкости между проводами

        a_uid = ''
        for ch in self.wire_a.id:
            a_uid += f"\\suka{str(ord(ch)).rjust(4, '0')}"

        b_uid = ''
        for ch in self.wire_b.id:
            b_uid += f"\\suka{str(ord(ch)).rjust(4, '0')}"

        # Проверяем на пересечение узлами отрезков
        if d_a1b1 + d_a2b1 == d_compare \
                or d_a1b2 + d_a2b2 == d_compare \
                or d_a1b1 + d_a1b2 == d_current \
                or d_a2b1 + d_a2b2 == d_current:
            raise Exception(f"Cable crossing: {a_uid} with {b_uid}")
        """
        Определения положения двух отрезков относительно друг друга:
        - соосно CE = 0
        - параллельно
        - общий случай
        """
        if cos_segment in (
                1, -1):  # два отрезка распаложенны параллельно либо соосно
            half_perimeter = (d_a1b1 + d_a2b1 + d_compare) / 2
            max_sides_triangle = max(d_a1b1, d_a2b1, d_compare)
            if half_perimeter == max_sides_triangle:  # соблюдение критерия соосности
                # отрезки расположенны относительно друг друга соосно
                # расстояние перекрытия между проекциями отрезков
                d = min(d_a1b1, d_a2b1, d_a1b2, d_a2b2)

                M = ct.NU / (4 * mt.pi) \
                    * ((d_compare + d_current + d)
                       * mt.log(d_compare + d_current + d) + d * mt.log(d)
                       - (d_compare + d) * mt.log(d_compare + d)
                       - (d_current + d) * mt.log(d_current + d)) * cos_segment
            else:
                # отрезки расположенны относительно друг друга паралельно
                s = (half_perimeter * (half_perimeter - d_compare) *
                     (half_perimeter - d_a2b1) *
                     (half_perimeter - d_a1b1))**0.5
                # расстояние между проводами
                h = round(2 * s / d_compare, 3)

                if cos_segment == 1:
                    h_a2b1 = round((d_a2b1**2 - h**2)**0.5, 3)
                    h_a2b2 = round((d_a2b2**2 - h**2)**0.5, 3)

                    if d_current + h_a2b1 == h_a2b2:
                        d = h_a2b1
                    else:
                        d = -h_a2b1
                else:
                    h_a1b1 = round((d_a1b1**2 - h**2)**0.5, 2)
                    h_a1b2 = round((d_a1b2**2 - h**2)**0.5, 2)

                    if d_current + h_a1b1 == h_a1b2:
                        d = h_a1b1
                    else:
                        d = -h_a1b1

                # алфа, бэта, гамма, дельта - совокупность отрезков для упрощения
                af = d_compare + d_current + d
                bt = d_compare + d
                gm = d_current + d
                dt = d

                M = ct.NU / (4 * mt.pi) \
                    * (af * mt.log(af + mt.hypot(af, h))
                       - bt * mt.log(bt + mt.hypot(bt, h))
                       - gm * mt.log(gm + mt.hypot(gm, h))
                       + dt * mt.log(dt + mt.hypot(dt, h))
                       - mt.hypot(af, h) + mt.hypot(bt, h)
                       + mt.hypot(gm, h) - mt.hypot(dt, h)) * cos_segment
        else:  # общий случай
            # Проверяем на пересечения кабелей
            complan = (self.a1.x - self.b1.x) * (p2z * p1y - p2y * p1z) \
                      - (self.a1.y - self.b1.y) * (p2z * p1x - p2x * p1z) \
                      + (self.a1.z - self.b1.z) * (p2y * p1x - p2x * p1y)
            if complan == 0:
                zero_xyz = np.array([0, 0, 0])

                ab1_x = (self.b1.z - self.a1.z) * p1y - (self.b1.y -
                                                         self.a1.y) * p1z
                ab1_y = -((self.b1.z - self.a1.z) * p1x -
                          (self.b1.x - self.a1.x) * p1z)
                ab1_z = (self.b1.y - self.a1.y) * p1x - (self.b1.x -
                                                         self.a1.x) * p1y
                ab2_x = (self.b2.z - self.a1.z) * p1y - (self.b2.y -
                                                         self.a1.y) * p1z
                ab2_y = -((self.b2.z - self.a1.z) * p1x -
                          (self.b2.x - self.a1.x) * p1z)
                ab2_z = (self.b2.y - self.a1.y) * p1x - (self.b2.x -
                                                         self.a1.x) * p1y
                ab1 = np.array([ab1_x, ab1_y, ab1_z])
                ab2 = np.array([ab2_x, ab2_y, ab2_z])
                p_ab1 = ab1 - zero_xyz
                p_ab2 = ab2 - zero_xyz
                d_ab1 = get_distance(zero_xyz, ab1)
                d_ab2 = get_distance(zero_xyz, ab2)
                cosab = get_cos(p_ab1, p_ab2, d_ab1, d_ab2)

                ba1_x = (self.a1.z - self.b1.z) * p2y - (self.a1.y -
                                                         self.b1.y) * p2z
                ba1_y = -((self.a1.z - self.b1.z) * p2x -
                          (self.a1.x - self.b1.x) * p2z)
                ba1_z = (self.a1.y - self.b1.y) * p2x - (self.a1.x -
                                                         self.b1.x) * p2y
                ba2_x = (self.a2.z - self.b1.z) * p2y - (self.a2.y -
                                                         self.b1.y) * p2z
                ba2_y = -((self.a2.z - self.b1.z) * p2x -
                          (self.a2.x - self.b1.x) * p2z)
                ba2_z = (self.a2.y - self.b1.y) * p2x - (self.a2.x -
                                                         self.b1.x) * p2y
                ba1 = np.array([ba1_x, ba1_y, ba1_z])
                ba2 = np.array([ba2_x, ba2_y, ba2_z])
                p_ba1 = ba1 - zero_xyz
                p_ba2 = ba2 - zero_xyz
                d_ba1 = get_distance(zero_xyz, ba1)
                d_ba2 = get_distance(zero_xyz, ba2)
                cosba = get_cos(p_ba1, p_ba2, d_ba1, d_ba2)

                if cosab == -1 and cosba == -1:
                    raise Exception(f"Cable crossing: {a_uid} with {b_uid}")

            # вычисление вектора нормали
            nx = p1y * p2z - p1z * p2y
            ny = -(p1x * p2z - p1z * p2x)
            nz = p1x * p2y - p1y * p2x

            # параметры плоскостей для каждого отрезка
            apl_compare = apl_current = nx
            bpl_compare = bpl_current = ny
            cpl_compare = cpl_current = nz
            dpl_compare = -nx * self.a1.x - ny * self.a1.y - nz * self.a1.z
            dpl_current = -nx * self.b1.x - ny * self.b1.y - nz * self.b1.z

            # параметр прямой заданной парамметрически которая является
            t1 = (-dpl_current - apl_current * self.a1.x -
                  bpl_current * self.a1.y - cpl_current * self.a1.z) / (
                      apl_current**2 + bpl_current**2 + cpl_current**2)
            # координаты точни a1нов
            a1bx = self.a1.x + t1 * apl_current
            a1by = self.a1.y + t1 * bpl_current
            a1bz = self.a1.z + t1 * cpl_current

            xy = xz = yz = 0
            if p1y * p2x - p2y * p1x != 0:
                xy = 100
            if p1z * p2x - p2z * p1x != 0:
                xz = 10
            if p1z * p2y - p2z * p1y != 0:
                yz = 1
            xyz = xy + xz + yz

            # находим координаты точки o2
            if xyz >= 100:
                o2x = (a1bx * p1y * p2x - self.b1.x * p2y * p1x - a1by * p1x *
                       p2x + self.b1.y * p1x * p2x) / (p1y * p2x - p2y * p1x)

                if p1x == 0:
                    ty = (o2x - self.b1.x) / p2x
                    o2y = p2y * ty + self.b1.y
                    o2z = p2z * ty + self.b1.z
                else:
                    tn = (o2x - a1bx) / p1x
                    o2y = p1y * tn + a1by
                    o2z = p1z * tn + a1bz
            elif xyz >= 10:
                o2z = (a1bz * p1x * p2z - self.b1.z * p2x * p1z - a1bx * p1z *
                       p2z + self.b1.x * p1z * p2z) / (p1x * p2z - p2x * p1z)

                if p1z == 0:
                    ty = (o2z - self.b1.z) / p2z
                    o2x = p2x * ty + self.b1.x
                    o2y = p2y * ty + self.b1.y
                else:
                    tn = (o2z - a1bz) / p1z
                    o2x = p1x * tn + a1bx
                    o2y = p1y * tn + a1by

            elif xyz >= 1:
                o2y = (a1by * p1z * p2y - self.b1.y * p2z * p1y - a1bz * p1y *
                       p2y + self.b1.z * p1y * p2y) / (p1z * p2y - p2z * p1y)

                if p1y == 0:
                    ty = (o2y - self.b1.y) / p2y
                    o2x = p2x * ty + self.b1.x
                    o2z = p2z * ty + self.b1.z
                else:
                    tn = (o2y - a1by) / p1y
                    o2x = p1x * tn + a1bx
                    o2z = p1z * tn + a1bz

            t2 = (-dpl_compare - apl_compare * o2x - bpl_compare * o2y -
                  cpl_compare * o2z) / (apl_current**2 + bpl_current**2 +
                                        cpl_current**2)

            o1x = o2x + t2 * apl_compare
            o1y = o2y + t2 * bpl_compare
            o1z = o2z + t2 * cpl_compare

            point_o1 = Point(np.array([o1x, o1y, o1z]))
            point_o2 = Point(np.array([o2x, o2y, o2z]))
            # расстояние между плоскостями
            h = get_distance(point_o1, point_o2)

            x1 = get_distance(point_o1, self.a1)
            x2 = get_distance(point_o1, self.a2)

            y1 = get_distance(point_o2, self.b1)
            y2 = get_distance(point_o2, self.b2)

            if round(abs(d_compare - x2) - x1, 3) != 0:
                x2 = -x2
            x1 = x2 - d_compare

            if round(abs(d_current - y2) - y1, 3) != 0:
                y2 = -y2
            y1 = y2 - d_current

            fi = mt.acos(cos_segment)

            if h != 0:
                AM = mt.atan((x1 + y1 + d_a1b1) / h * mt.tan(fi / 2)) \
                     + mt.atan((x2 + y2 + d_a2b2) / h * mt.tan(fi / 2)) \
                     - mt.atan((x1 + y2 + d_a1b2) / h * mt.tan(fi / 2)) \
                     - mt.atan((x2 + y1 + d_a2b1) / h * mt.tan(fi / 2))
            else:
                AM = 0

            M = 2 * ct.NU / (4 * mt.pi) * cos_segment \
                * (x2 * mt.atanh(d_current / (d_a2b2 + d_a2b1))
                   + y2 * mt.atanh(d_compare / (d_a2b2 + d_a1b2))
                   - x1 * mt.atanh(d_current / (d_a1b1 + d_a1b2))
                   - y1 * mt.atanh(d_compare / (d_a1b1 + d_a2b1))
                   + h / mt.sin(fi) * AM)

        # Блок вычисления Емкосного воздействия
        # Если метализация есть хотябы на одном проводе то Uc12 = 0
        Uc12 = 0
        if not (self.wire_a.get_is_metallization()
                or self.wire_b.get_is_metallization()) and cos_segment != 0:
            if cos_segment > 0:
                cos_alfa1 = get_cos(p_a1a2, self.b1 - self.a1, d_compare,
                                    d_a1b1)
                cos_alfa2 = get_cos(self.a1 - self.a2, self.b2 - self.a2,
                                    d_compare, d_a2b2)

                if (cos_alfa1 >= 0 and cos_alfa2 >= 0) or (cos_alfa1 <= 0
                                                           and cos_alfa2 <= 0):
                    Up = 1
                else:  # если оба косинуса имеют разные знаки
                    Up = max(mt.sin(mt.acos(cos_alfa1)),
                             mt.sin(mt.acos(cos_alfa2)))

            else:  # cos_segment < 0
                cos_alfa1 = get_cos(p_a1a2, self.b2 - self.a1, d_compare,
                                    d_a1b2)
                cos_alfa2 = get_cos(self.a1 - self.a2, self.b1 - self.a2,
                                    d_compare, d_a2b1)

                if cos_alfa1 * cos_alfa2 < 0:
                    Up = max(mt.sin(mt.acos(cos_alfa1)),
                             mt.sin(mt.acos(cos_alfa2)))
                else:
                    Up = 1

            # длина влияния расматриваемых отрезков проводов
            de = min(d_compare, d_current) * Up * cos_segment
            # найдем растояние между фрагментами
            he = get_distance((self.a1 + self.a2) / 2, (self.b1 + self.b2) / 2)
            # найдем среднеарифиметическое значение диаметров жил взаимовлияющих проводов
            diam = (self.wire_a.diam + self.wire_b.diam) / 2
            # найдем виличину электрической емкости между отрезками проводов
            if he != 0:
                CE = (mt.pi * ct.EPS) / mt.log((2 * he) / diam +
                                               ((he / diam)**2 - 1)**0.5) * de
                # найдем емкостное сопротивление
                Zc = abs(1 / (self.wire_a.w * CE))
                # найдем сумарное сопротивление на портах провода b
                Zb = self.wire_b.R1 + self.wire_b.R2
                # найдем напряжение переданное от провода a к проводу b
                Uc12 = self.wire_a.U * Zb / (Zb + Zc)
            else:
                Uc12 = 0

        return Uc12, M
import functions

functions.print_result(
    functions.calculate_steps(functions.get_distance(),
                              functions.get_step_length()))
Пример #17
0
    def do(self, is_magnetic=False):
        """
        Основной алгоритм действий
        :param is_magnetic: False - расчет для электрической состовляющей, True - расчет для магнитной состовляющей
        """
        # Находим разницу
        p = self.C - self.U
        # Находим параметры квадратного уравнения ax2 + bx + c = 0
        a = (p**2).sum()

        f = self.f  # для сокращения

        res = 0  # значения ослабления магнитной или электрической составляющей
        for figure in self.figures:
            o = figure.point
            r = figure.r
            po = self.C - o

            b = (po * p).sum() * 2
            c = (po**2).sum() - r**2

            # Найдем дискриминант
            d = b**2 - 4 * a * c

            if d > 0:
                # Находим корни квадратного уравнения
                t1 = (-b - d**0.5) / (2 * a)
                t2 = (-b + d**0.5) / (2 * a)

                # Найдем точки пересечения сферы с прямой
                T1 = t1 * p + self.C
                T2 = t2 * p + self.C

                # Найдем толщину экрана
                dT = get_distance(T1, T2)

                # Найдем радиус экрана
                re = min(get_distance(self.U, T1), get_distance(self.U, T2))

                # TODO если в справочнике такого материала нет берется материал по умолчанию
                # TODO не учитываем то что значения может и не быть в нужном столбце
                # Найдем проводимость материала фигуры, относительно меди

                try:
                    ec = self.materials.get(figure.material_id,
                                            ct.MATERIAL_DEFAULT)[1] / ct.EC_CU

                    # Найдем относительную магнитную проницаемость материала фигуры, относительно меди
                    nu = self.materials.get(figure.material_id,
                                            ct.MATERIAL_DEFAULT)[2] / ct.NU_CU
                except Exception:
                    ec = ct.MATERIAL_DEFAULT[1] / ct.EC_CU
                    nu = ct.MATERIAL_DEFAULT[2] / ct.NU_CU

                if is_magnetic:  # расчет для магнитной состовляющей
                    res += 14.6 + 10 * math.log10(
                        (f * re**2 * ec) / nu) + 131.4 * dT * (f * nu *
                                                               ec)**0.5
                else:  # расчет для электрической состовляющей
                    res += 332 + 10 * math.log10(
                        ec /
                        (re**2 * f**3 * nu)) + 131.4 * dT * (f * nu * ec)**0.5

        # Перевод полученного значения в разы
        res = 10**-(res / 20)

        return res
Пример #18
0
def get_places_by_date_time():
    cur_path = change_path_to_data()
    conn = sqlite3.connect('data.db')
    c = conn.cursor()

    new_places = []

    for u in range(0, 10):
        user = get_folder(u)

        # Get all dates from the database
        query = "SELECT DISTINCT dated FROM master" + user  # 6367 for 000, 256 for 001
        dates = []
        for line in c.execute(query):
            dates.append(line[0])

        places = []

        # places.append([172042, 39.955832, 116.329224, '2009-07-05', '04:44:31'])
        # For each date in the database, get all the locations and extract places based on 10 minute difference
        for d in dates:
            query = "SELECT * FROM master" + user + " WHERE dated = '" + str(
                d) + "'"
            # print(query)
            prev = 0
            for line in c.execute(query):
                line = list(line)
                line[4] = line[4][:-1]
                if prev == 0:
                    # print(line, prev)
                    places.append(line)
                    prev += 1
                else:
                    minutes = get_minutes(places[prev - 1][4], line[4])
                    # print(minutes)
                    if minutes > 15:
                        distance = get_distance(places[prev - 1][1:3],
                                                line[1:3])
                        if distance > 20:
                            if line not in places:
                                # line.append(1)
                                # print(line, minutes, distance)
                                places.append(line)
                                prev += 1

        # Add entries to new_places
        initial = len(new_places)
        if len(new_places) == 0:
            for p in places:
                p.append(1)
                new_places.append(p)
        else:
            for p in places:
                index = find_place_linear(new_places, p)
                if index == -1:
                    p.append(1)
                    new_places.append(p)
                else:
                    new_places[index][5] += 1

        print("User: "******"Number of places: ", len(places))
        print("Number of places added: ", len(new_places) - initial)

    # print(new_places)
    print("Total new places: ", len(new_places))
    # Remove entries from new_places table
    query = "DELETE FROM new_places"
    c.execute(query)
    query = "DELETE FROM sqlite_sequence WHERE NAME = 'new_places'"
    c.execute(query)

    for place in new_places:
        c.execute(
            "INSERT INTO new_places(latitude, longitude, dated, timed, weight) VALUES (?, ?, ?, ?, ?)",
            place[1:])
        # print(place[0:4])

    conn.commit()
    conn.close()
    back_to_path(cur_path)
Пример #19
0
    def do(self, limit_a=0, is_bba=False):
        """
        Основной алгоритм действий
        :param is_bba: если False расчет проводится для фрагмента провода иначе для ББА
        """
        if self.wire.get_is_metallization(
        ):  # если присутсвует на кабеле метализация то мы не рассчитываем алгоритм
            return np.zeros(3), 0

        # Вычисляем волновое число
        wk = self.wire.w / ct.CC

        if is_bba:
            r = get_distance(self.BBA.point, self.C)
            w = 2 * mt.pi * self.BBA_f
            er = self.BBA_E * ((1 / (w * r**3) - w / (r * ct.CC**2) + 1 /
                                (ct.CC * r**2)) /
                               (1 / w - w / ct.CC**2 + 1 / ct.CC))
            return er
        """
        Вычисления:
        - вектора прямой
        - r0-rC
        - (r0-rC)*p
        - pp
        """
        # вычисления вектора прямой
        pxyz = self.X1 - self.X0
        # вычисление r0-rC
        r0rc = self.X0 - self.C
        # вычисление (r0-rC)*p
        r0rc_p = (r0rc * pxyz).sum()
        # вычисление p*p
        pp = (pxyz**2).sum()
        """
        Вычисление rb
        """
        rb = self.X0 - r0rc_p / pp * pxyz
        """
        Вычисления:
        - пределов a b
        - проекции С
        """
        # итерационный блок вычисления пределов a b
        limit_b = pp
        # итерационный блок вычисления проекции С
        n = ((rb - self.X0)**2).sum()
        h = ((self.C - rb)**2).sum()
        # блок вычисления пределов a b
        limit_b = limit_b**0.5 + limit_a
        # блок вычисления проекции С
        n = n**0.5 + limit_a
        h = h**0.5
        """
        Алгоритм Start
        """
        count_iter = 100

        dx = (limit_b - limit_a) / count_iter

        # искомые элементы напряженности
        erx = 0
        ery = 0
        ettx = 0
        etty = 0
        for it in range(count_iter):
            x = it * dx + dx / 2 + limit_a
            xt = it * dx + limit_a
            bx = n - x
            r = (bx**2 + h**2)**0.5

            costt = bx / r
            sintt = h / r

            dl = self.wire.I * (
                1 / wk *
                (mt.cos(self.wire.w *
                        (self.t -
                         (xt + dx) / ct.CC)) - mt.cos(self.wire.w *
                                                      (self.t - xt / ct.CC))) -
                dx * mt.sin(self.wire.w * self.t)) / 2

            erx += wk * dl / (2 * mt.pi * ct.EPS * self.wire.w * r**2) * (
                mt.sin(self.wire.w * self.t - wk * r) /
                (wk * r) + mt.cos(self.wire.w * self.t - wk * r)) * costt**2
            ery += wk * dl / (2 * mt.pi * ct.EPS * self.wire.w * r**2) * (
                mt.sin(self.wire.w * self.t - wk * r) / (wk * r) +
                mt.cos(self.wire.w * self.t - wk * r)) * costt * sintt

            ettx -= wk**2 * dl / (4 * mt.pi * ct.EPS * self.wire.w * r) * (
                mt.cos(self.wire.w * self.t - wk * r) / (wk * r) +
                (1 / ((wk * r)**2) - 1) *
                mt.sin(self.wire.w * self.t - wk * r)) * sintt**2
            etty += wk**2 * dl / (4 * mt.pi * ct.EPS * self.wire.w * r) * (
                mt.cos(self.wire.w * self.t - wk * r) / (wk * r) +
                (1 / ((wk * r)**2) - 1) *
                mt.sin(self.wire.w * self.t - wk * r)) * sintt * costt

        ex = erx + ettx
        ey = ery + etty
        """
        Алгоритм End
        """
        """
        Переход от локальных к базовым координатам
        """

        lbx = pxyz / (limit_b - limit_a)
        lby = Point(np.array([0, 0, 0]))
        if h != 0:
            lby = (self.C - rb) / h

        # финальные значения по координатам
        ec = ex * lbx + ey * lby

        # ослабление электрической составляющей экраном провода
        ec = ec * self.wire.SE

        return ec.point, limit_b
Пример #20
0
def reduce_inputs_func(inputs_files, outputs_dir, options_verbose):
    """From a set of input pairs (.pdb) compares each chain pair with the rest. This comparision has two steps: sequence
    and structural. First of all, a pairwise alignment is performed to determine similar sequences (cut-off = 0.9).
    The score of the alignment is normalized by the length of the longest sequence. If the normalized score is higher
    than the stablished cut-off, the analysis proceeds to the second step. In this step, a superimposition is performed
    between the similar chains. These similar chains are part of two different interaction pairs, which will be refered
    as fixed and moving chains. We apply the rotran matrix to the couple of the moving chain, which will be refered as
    alternative/new chain. Finally, the distances between the CA of the comparing chain (couple of the fixed chain) and
    the new chain are computed. If the distance is lower than 9A, the interactions will be considered the same (redundant)."""

    import functions
    if options_verbose:
        sys.stderr.write(
            "\nGetting the non-redundant interactions... Please wait.\n\n")
    PDBparser = Bio.PDB.PDBParser()

    # Creating a list of lists of the input pairs
    list_of_pairs = []
    for pair in inputs_files:
        input_pair_list = []
        pdb_code = pair.split("/")[-1].split(".")[0]
        pdb_filename = pair
        structure = PDBparser.get_structure(pdb_code, pdb_filename)
        for model in structure:
            for chain in model:
                input_pair_list.append(chain)
        list_of_pairs.append(input_pair_list)

    # Cut-off to determine similarity between chain sequences. If the chain cut-off is greater than the specified cut-off,
    # these chains will be considered equal for the superimposition.
    cutoff = 0.9
    c = 0
    redundancy_list = []
    for pair0 in list_of_pairs:
        c += 1
        for pair1 in list_of_pairs[c:]:

            for chain in pair1:
                pair00_seq = functions.get_seq_from_pdbchain(pair0[0])
                chain_seq = functions.get_seq_from_pdbchain(chain)
                alignments = pairwise2.align.globalxx(pair00_seq, chain_seq)

                if len(alignments) > 0:
                    score_chain = alignments[0][2]
                    len_max = max(len(pair00_seq), len(chain_seq))
                    cutoff_chain = score_chain / len_max

                    if cutoff_chain >= cutoff:
                        fixedchain = pair0[0]
                        movingchain = chain
                        pair1_to_pop = copy.copy(pair1)
                        pair1_to_pop.pop(pair1.index(movingchain))
                        altchain = pair1_to_pop[0]
                        comparingchain = pair0[1]

                        fixed_atoms_list = functions.get_atoms_list(fixedchain)
                        moving_atoms_list = functions.get_atoms_list(
                            movingchain)

                        new_chain = Bio.PDB.Chain.Chain("X")
                        altchain = copy.copy(altchain)
                        for residue in altchain.get_residues():
                            new_chain.add(residue.copy())

                        if len(fixed_atoms_list) != len(moving_atoms_list):
                            chains_pattern = functions.refine_for_superimpose(
                                fixedchain, movingchain)
                            fixed_pattern = chains_pattern[0]
                            moving_pattern = chains_pattern[1]

                            fixedchain = functions.get_chain_refined(
                                fixedchain, fixed_pattern)
                            movingchain = functions.get_chain_refined(
                                movingchain, moving_pattern)

                            fixed_atoms_list = functions.get_atoms_list(
                                fixedchain)
                            moving_atoms_list = functions.get_atoms_list(
                                movingchain)

                        super_imposer = Bio.PDB.Superimposer()
                        super_imposer.set_atoms(fixed_atoms_list,
                                                moving_atoms_list)
                        super_imposer.apply(new_chain.get_atoms())

                        new_chain_atoms_list = functions.get_atoms_list(
                            new_chain)
                        comparing_chain_atoms_list = functions.get_atoms_list(
                            comparingchain)

                        if len(new_chain_atoms_list) != len(
                                comparing_chain_atoms_list):
                            chains_pattern = functions.refine_for_superimpose(
                                new_chain, comparingchain)
                            new_pattern = chains_pattern[0]
                            comparing_pattern = chains_pattern[1]
                            new_chain = functions.get_chain_refined(
                                new_chain, new_pattern)
                            comparingchain = functions.get_chain_refined(
                                comparingchain, comparing_pattern)

                            new_chain_atoms_list = functions.get_atoms_list(
                                new_chain)
                            comparing_chain_atoms_list = functions.get_atoms_list(
                                comparingchain)

                        if len(new_chain_atoms_list) == 0 or len(
                                comparing_chain_atoms_list) == 0:
                            break

                        distances = []
                        for new_atom, comparing_atom in zip(
                                new_chain_atoms_list,
                                comparing_chain_atoms_list):
                            coords_new = new_atom.get_coord()
                            coords_comparing = comparing_atom.get_coord()
                            distance = functions.get_distance(
                                list(coords_new.tolist()),
                                list(coords_comparing.tolist()))
                            distances.append(distance)

                        max_distance = max(distances)
                        if max_distance < 9:
                            pairs = [pair0, pair1]
                            redundancy_list.append(pairs)
                else:
                    continue

    to_delete_pair = []
    for pairs in redundancy_list:
        to_delete_pair.append(pairs[1])

    final_inputs = copy.copy(list_of_pairs)
    for pair in to_delete_pair:
        for pair2 in final_inputs:
            if pair[0] == pair2[0] and pair[1] == pair2[1]:
                idx = final_inputs.index(pair)
                del final_inputs[idx]

    number_file = 1
    for element in final_inputs:
        save_new_pair(element[0], element[1], outputs_dir, number_file)
        number_file += 1
    if options_verbose:
        sys.stderr.write(
            "The total number of redundant interactions found is %d\n" %
            (len(redundancy_list)))
        sys.stderr.write(
            "The final number of non-redundant interactions is %d\n" %
            (len(final_inputs)))

    return "OK"