Esempio n. 1
0
    def test_buildup_of_integer_basis_matrix_of_orthogonal_complement_of_stoichiometric_matrix_column_basis(
            self):

        print(
            "test_buildup_of_integer_basis_matrix_of_orthogonal_complement_of_stoichiometric_matrix_column_basis..."
        )
        #columns form generators of stoichiometric subspace
        stoichiometric_matrix = MatrixUtils.build_stoichiometric_matrix_from_messi_network(
            messi_network)

        #Matriz alta...o larga? Creo que larga.
        stoichiometric_matrix_column_basis = MatrixUtils.extract_column_basis(
            stoichiometric_matrix)

        ortoghonal_complement_of_stoichiometric_matrix_column_basis = \
            MatrixUtils.build_integer_basis_matrix_of_orthogonal_complement_of_matrix(stoichiometric_matrix_column_basis, True)

        #Quizas haya que transponer...

        #Es el nucleo a derecha
        #product1 = ortoghonal_complement_of_stoichiometric_matrix_column_basis @ stoichiometric_matrix_column_basis
        product = stoichiometric_matrix_column_basis @ ortoghonal_complement_of_stoichiometric_matrix_column_basis

        #self.assertTrue(np.linalg.matrix_rank(product1) == 0)
        self.assertTrue(np.linalg.matrix_rank(product) == 0)

        stoch_shape = np.shape(stoichiometric_matrix)
        complement_shape = np.shape(
            ortoghonal_complement_of_stoichiometric_matrix_column_basis)
        print("OK")

        #NO ANDA, sera porque la matriz no es realista?
        """M = np.array([[ 0,  0,  1,  0,  0,  0],
             [ 1,  1,  0,  0,  1,  0],
             [ 0,  0,  0,  1,  0,  1]])

        M_orthogonal_complement = MatrixUtils.build_integer_basis_matrix_of_orthogonal_complement_of_matrix(M, False)

        product = M @ M_orthogonal_complement
        self.assertTrue(np.linalg.matrix_rank(product) == 0)"""

        print("OK")
Esempio n. 2
0
    def test_build_binomial_matrix(self):
        print("test_build_binomial_matrix...")
        species_names = ['X1', 'X2', 'X3', 'X4']
        species = range(0, 4)
        complexes = [0, 1, 2, 3]
        complexes_names = complexes
        reactions = [[0, 3, None], [1, 2, None], [2, 1, None], [3, 2, None],
                     [2, 0, None]]

        G2_circle = nx.DiGraph(directed=True)

        sources = set([reaction[0] for reaction in reactions])

        targets = set([reaction[1] for reaction in reactions])

        nodes = sources.union(targets)
        G2_circle.add_nodes_from(nodes)
        for reaction in reactions:
            G2_circle.add_edge(reaction[0],
                               reaction[1],
                               reaction_constant=reaction[2])

        #So that it has no intermediates
        partitions = [[], [0, 1, 2, 3, 4]]
        partitions_names = [[], species]

        messi_network = MESSINetworkBuilder.MESSINetwork(test=True)

        messi_network.G2 = G2_circle
        messi_network.partitions = partitions
        messi_network.partitions_names = partitions_names
        messi_network.G2_circle = G2_circle
        messi_network.partitions = partitions
        messi_network.species = species

        binomial_matrix = MatrixUtils.build_binomial_matrix(messi_network)

        binomial_matrix_result = np.array([[1, 0, 0], [0, 1, 0], [0, -1, 1],
                                           [-1, 0, 1]])

        self.assertTrue(
            np.linalg.matrix_rank(binomial_matrix) == np.linalg.matrix_rank(
                binomial_matrix_result))

        concatenated_matrix = np.concatenate(
            (binomial_matrix, binomial_matrix_result), axis=0)
        rank1 = np.linalg.matrix_rank(concatenated_matrix)
        rank2 = np.linalg.matrix_rank(binomial_matrix)

        self.assertTrue(rank1 == rank2)

        np.linalg.matrix_rank

        print("OK")
Esempio n. 3
0
    def test_buildup_of_complexes_matrix_from_network(self):
        print("test_buildup_of_complexes_matrix_from_network...")
        complexes_matrix = MatrixUtils.build_complexes_matrix(messi_network)
        complexes_matrix_solution = np.array([[1, 0, 0, 0, 1, 0],
                                              [0, 1, 0, 0, 1, 0],
                                              [0, 0, 1, 0, 0, 0],
                                              [1, 0, 0, 0, 0, 1],
                                              [0, 1, 0, 0, 0, 1],
                                              [0, 0, 0, 1, 0, 0]])

        self.assert_same_columns(complexes_matrix, complexes_matrix_solution)
        print("OK")
Esempio n. 4
0
    def test_buildup_of_stoichiometric_matrix_from_network(self):

        print("test_buildup_of_stoichiometric_matrix_from_network...")
        incidence_matrix = MatrixUtils.build_incidence_matrix(messi_network)
        complexes_matrix = MatrixUtils.build_complexes_matrix(messi_network)

        stoichiometric_matrix = MatrixUtils.build_stoichiometric_matrix(
            incidence_matrix, complexes_matrix)

        #print("stoichiometric_matrix")
        #print(stoichiometric_matrix)

        #rango 3

        stoichiometric_matrix_solution = np.array([[-1, 1, 0, 0, 1, 0],
                                                   [0, 0, 1, -1, 0, 1],
                                                   [1, -1, -1, 0, 0, 0],
                                                   [0, 0, 0, 1, -1, -1],
                                                   [-1, 1, 1, 0, 0, 0],
                                                   [0, 0, 0, -1, 1, 1]])

        self.assert_same_columns(stoichiometric_matrix,
                                 stoichiometric_matrix_solution)
        print("OK")
Esempio n. 5
0
    def test_buildup_of_incidence_matrix_from_network(self):
        print("test_buildup_of_incidence_matrix_from_network")
        """reactions = [
        ['S0+E', 'ES0','k1'],
        ['ES0', 'S0+E', 'k2'],
        ['ES0', 'S1+E','k3'],
        ['S1+F', 'FS1', 'k4'],
        ['FS1', 'S1+F', 'k5'],
        ['FS1', 'S0+F', 'k6']
        ]"""

        #The complexes are labeled y0, y1, y...

        incidence_matrix = MatrixUtils.build_incidence_matrix(messi_network)
        """I_solution = np.array([
        [-1, 1, 0, 0, 0, 0],
        [1, -1, -1, 0, 0, 0],
        [0, 0, 1, 0, 0, 0],
        [0, 0, 0, -1, 1, 0],
        [0, 0, 0, 1, -1, -1],
        [0, 0, 0, 0, 0, 1]
        ])"""
        """

        reactions = [
    ['0', '2','k1'],
    ['2', '0', 'k2'],
    ['2', '1','k3'],
    ['4', '5', 'k4'],
    ['5', '4', 'k5'],
    ['5', '3', 'k6']
    ] """

        incidence_matrix_solution = np.array([[-1, 1, 0, 0, 0, 0],
                                              [0, 0, 1, 0, 0, 0],
                                              [1, -1, -1, 0, 0, 0],
                                              [0, 0, 0, 0, 0, 1],
                                              [0, 0, 0, -1, 1, 0],
                                              [0, 0, 0, 1, -1, -1]])

        #The incidence matrix might have columns in another order.
        self.assert_same_columns(incidence_matrix, incidence_matrix_solution)
        print("OK")
Esempio n. 6
0
    def test_buildup_of_educt_complexes_matrix_from_network(self):
        print("test_buildup_of_educt_complexes_matrix_from_network...")
        #G = get_24_toric_graph()
        """
        S0+E   --> y0
        S1+E   --> y1
        ES0    --> y2
        S0 + F --> y3
        S1 + F --> y4
        FS1    --> y5
        """
        """
        S0  --> x0
        S1   --> x1
        ES0 --> x2
        FS1  --> x3
        E   --> x4
        F --> x5
        """

        educt_complexes_matrix = MatrixUtils.build_educt_complexes_matrix(
            messi_network)
        """
        ordered educts:
        s0+e, es0, es0, s1+f, fs1, fs1

        that is:
        x0+x4, x2, x2, x1+x5, x3, x3

        """

        educt_complexes_matrix_solution = np.array([[1, 0, 0, 0, 0, 0],
                                                    [0, 0, 0, 1, 0, 0],
                                                    [0, 1, 1, 0, 0, 0],
                                                    [0, 0, 0, 0, 1, 1],
                                                    [1, 0, 0, 0, 0, 0],
                                                    [0, 0, 0, 1, 0, 0]])

        self.assert_same_columns(educt_complexes_matrix,
                                 educt_complexes_matrix_solution)
        print("OK")
 def _calc_diff_matrices_a(self):
     """
     Calculates the matrices of differences in activations between neighbouring pixels, used to
     calculate the absolute value smoothness regularization
     :return: diff matrix with the pixel above, below, left, right, diagonally down, and diagonally up
     """
     a_matr = self.a_matr.T.reshape(self.x_shape[0], self.x_shape[1],
                                    self.p_).copy()
     a_down = MatrixUtils.shift_matrix_vert(a_matr, 1)
     a_up = MatrixUtils.shift_matrix_vert(a_matr, -1)
     a_left = MatrixUtils.shift_matrix_horiz(a_matr, 1)
     a_right = MatrixUtils.shift_matrix_horiz(a_matr, -1)
     a_diag_down = MatrixUtils.shift_matrix_diag(a_matr, 1)
     a_diag_up = MatrixUtils.shift_matrix_diag(a_matr, -1)
     return (a_matr - a_down, a_matr - a_up, a_matr - a_left,
             a_matr - a_right, a_matr - a_diag_down, a_matr - a_diag_up)
Esempio n. 8
0
def process_pdf():
    network = request.form.get("network")
    partition = request.form.get("partitions")

    print('network', network)
    print('partition', partition)

    network_rows = network.split('\n')
    partition_rows = partition.split('\n')

    sys.stdout.flush()

    #return json.dumps({"kappa": "GOL"})

    messi_network = MESSINetworkBuilder.get_network_from_text(
        network_rows, partition_rows)

    # for easier reading
    # Bperp, Mt = HardcodedUtils.get_hardcoded_matrices()

    Mperp = MatrixUtils.build_integer_basis_of_orthogonal_complement_of_stoichiometric_matrix(
        messi_network)

    # rint('Mperp', Mperp)

    Bt = MatrixUtils.build_binomial_matrix(messi_network).transpose()

    # print('Bt', Bt)

    # print("Mperp", Mperp)
    # print("Bt", Bt)

    # print("species names")
    # print(messi_network.species_names)
    # print("______________________")

    toric_N = MatrixUtils.build_stoichiometric_matrix_from_messi_network(
        messi_network)

    # print('toric_N', toric_N)

    M = MatrixUtils.build_integer_basis_of_stoichiometric_matrix(messi_network)

    # print('M', M)

    Bperp = MatrixUtils.build_integer_basis_of_orthogonal_complement_of_binomial_matrix(
        messi_network)
    # print('Bperp', Bperp)

    # print("M - sus filas son una base de S")
    # print(M)

    # print("Stochiometric matrix - las filas generan S")
    stochiometric_matrix2 = MatrixUtils.build_stoichiometric_matrix_from_messi_network(
        messi_network)

    # print('stoichiometrix matrix', stochiometric_matrix2)

    # print(stochiometric_matrix2.transpose())

    # TODO: finish this MESSINetworkBuilder function instead of using hardcoded Bperp and Mt.
    # The function should return BPerp and Mt from user input of the MESSI system.
    # MESSINetworkBuilder.get_relevant_matrices(debug)

    # From now on, almost everything is automated

    # Columns of B^\perp
    # Poner asserts correctos...

    # s = #columnas Bperp
    # s es la cantidad de columnas de Bt
    # d es la cantidad de filas de Mperp

    d = np.shape(Mperp)[0]
    s = np.shape(Mperp)[1]

    # toric M
    positive_Mperp = MatrixUtils.build_positive_integer_basis_of_kernel_of_stoichiometric_matrix(
        messi_network)
    educt_complexes_matrix = MatrixUtils.build_educt_complexes_matrix(
        messi_network)

    show_matrices = True
    # alternative_Mperp = MatrixUtils.build_alternative_positive_integer_basis_of_ortogonal_complement_of_stoichiometric_matrix(messi_network)
    if show_matrices:
        print('.' * 30)
        print('.' * 30)
        print("Complexes: ")
        print(messi_network.complexes)

        print("Complexes names:")
        print(messi_network.complexes_names)

        print("Species:")
        print(messi_network.species)

        print("Species names:")
        print(messi_network.species_names)

        print('Partitions')
        print(messi_network.partitions_names)

        print("Mperp")
        print(Mperp)

        print("positive M perp")
        print(positive_Mperp)

        print("M")
        print(M)

        print("educt complexes matrix")
        print(educt_complexes_matrix)

        print("Bt transpose")
        print(Bt.transpose())

        print("d", d)

        print("s", s)

        print("stoichiometric matrix", stochiometric_matrix2)

        print("Bperp", Bperp)

        print("toric N", toric_N)

        print('alternative Mperp')

        # print(alternative_Mperp)

        print('.' * 30)
        print('.' * 30)

    sys.stdout.flush()

    # input("")
    # print("d")
    # print(d)
    # print("s")
    # print(s)

    Mt = M.transpose()

    # print("We now compute Sigma_perp and check if it is mixed. Press ENTER to continue.")
    # input()

    # exits if false
    print(
        "Checking if the system is multisatationary by checking Sigma's signs..."
    )
    is_mixed = SigmaUtils.check_if_sigma_subperp_is_mixed(M, Bperp, s, d)
    if not is_mixed:
        return json.dumps({'kappa': False})

    circuits_information_M = CircuitUtils.CircuitsInformation(M)

    circuits_information_Bperp = CircuitUtils.CircuitsInformation(Bperp)

    # Steps 2-5

    only_one_string = 'Yes'

    # only_one = False
    equal_sign_vectors = []
    only_one = False
    if 'y' in only_one_string.lower() or len(only_one_string) == 0:
        only_one = True
        print("Getting only one pair of equal sign vectors...")
        equal_sign_vectors = CircuitUtils.get_only_one_equal_sign_vector(
            s, circuits_information_Bperp, circuits_information_M)
    else:
        print("Getting all equal sign vectors...")
        equal_sign_vectors = CircuitUtils.get_equal_sign_vectors(
            s, circuits_information_Bperp, circuits_information_M)

    # print(M)
    # print(Bperp)
    # exit(0)

    print("We now compute multistationarity witnesses...")
    sys.stdout.flush()
    found_kappa = False
    if len(equal_sign_vectors) == 0:
        return json.dumps({'kappa': False})
    else:

        max_number = 0
        files = [
            name for name in os.listdir('./outputs')
            if os.path.isfile('./outputs/' + name)
        ]
        for filename in files:
            try:
                dot_index = filename.index('.')
                number = int(filename[7:dot_index])
                max_number = max(max_number, number)
            except ValueError:
                continue
        output_filename = 'outputs/output_%d.log' % (max_number + 1)

        print('Saving the output in ' + output_filename + '\n')
        with open(output_filename, 'w') as f:
            if not only_one:
                print(
                    "For each solution orthant, we will now produce the steady states x1 and x2, and the reaction constants kappa..."
                )
            else:
                print(
                    "We will now produce the steady states x1 and x2, and the reaction constants kappa, for the pair of equal sign vectors found..."
                )
                f.write('(Only 1 pair of steady states was searched for)\n')

            f.write('Species' + '\n')
            f.write(str(messi_network.species_names) + '\n\n')
            f.write('Complexes' + '\n')
            f.write(str(messi_network.complexes_names) + '\n\n')
            f.write('Partitions' + '\n')
            f.write(str(messi_network.partitions_names) + '\n\n')
            f.write('G' + '\n')
            f.write(str(messi_network.G.edges(data=True)) + '\n\n')

            ret = ""
            # f.write('G1', messi_network.G1.edges(data=True))
            # f.write('G1', messi_network.G2.edges(data=True))
            # f.write('G2_circle', messi_network.G2_circle.edges(data=True))

            # We iterate the list equal_sign_vectors, while simultaneously generating counter "index"
            for index, L in enumerate(equal_sign_vectors):

                # Here, %d is replaced by index+1.

                first_solution = L
                v = first_solution[0]  # viene de Stoc
                w = first_solution[1]  # Viene de binomios

                x1, x2 = Utils.get_multistationarity_witnesses(w, v, s, d)

                # Step 6
                # TODO: there are some hardcoded stuff inside this function
                kappa = Utils.get_kappa2(x1, x2, positive_Mperp,
                                         educt_complexes_matrix, messi_network,
                                         toric_N)

                if isinstance(kappa, list):
                    found_kappa = True
                    print('Concentrations for x1:')
                    CX1 = ''
                    for index, val in enumerate(x1):
                        CX1 += '%s: %s | ' % (
                            messi_network.species_names[index], str(val))
                    CX1 = CX1[:-3]
                    print(CX1)

                    print('')
                    print('Concentrations for x2:')
                    CX2 = ''
                    for index, val in enumerate(x2):
                        CX2 += '%s: %s | ' % (
                            messi_network.species_names[index], str(val))
                    CX2 = CX2[:-3]
                    print(CX2)

                    print('')
                    print('Reaction constants:')
                    Ck = ''
                    for index, val in enumerate(kappa):
                        Ck += '%s: %s | ' % (
                            messi_network.constants_names[index], str(val))
                    Ck = Ck[:-3]
                    print(Ck)

                    print('')
                    print('Total Amounts:')

                    total_amounts_vec = []
                    TA_toprint = ''
                    for relation in messi_network.linear_relations:
                        species_text = ''
                        total_value = 0
                        for species in relation:
                            total_value += x1[species]
                            species_text += messi_network.species_names[
                                species] + ' + '
                        total_amounts_vec.append(total_value)
                        species_text = species_text[:-3]
                        TA_toprint += ('%s = ' % species_text +
                                       "{:.6f}".format(total_value) + '\n')
                        print('%s = ' % species_text,
                              "{:.6f}".format(total_value))

                    all_OK = True
                    for index, relation in enumerate(
                            messi_network.linear_relations):
                        species_text = ''
                        total_value = 0
                        for species in relation:
                            total_value += x2[species]
                            species_text += messi_network.species_names[
                                species] + ' + '
                        species_text = species_text[:-3]

                        if abs(total_value - total_amounts_vec[index]) > 1e-3:
                            print('WARNING', species_text,
                                  'got a different result with x2.')
                            print('Value:', "{:.6f}".format(total_value))
                            all_OK = False
                        # print('%s = ' % species_text, "{:.6f}".format(total_value))
                    if all_OK:
                        print(
                            'Total Amounts were calculated with both x1 and x2 and the result did not change.'
                        )

                    f.write('Concentrations for x1:' + '\n')
                    f.write(CX1 + '\n\n')

                    f.write('Concentrations for x2:' + '\n')
                    f.write(CX2 + '\n\n')

                    f.write('Reaction constants:' + '\n')
                    f.write(Ck + '\n\n')

                    f.write('Total Amounts:' + '\n')
                    f.write(TA_toprint + '\n')
                    f.write("_______________________________________\n\n\n")

                    print("_______________________________________")

        return json.dumps({'kappa': found_kappa})

    return json.dumps({'answer': str(messi)})