Exemplo n.º 1
0
    def test_just_label(self):
        """Test that it can be called with no value."""
        st.beta_color_picker("the label")

        c = self.get_delta_from_queue().new_element.color_picker
        self.assertEqual(c.label, "the label")
        self.assertEqual(c.default, "#000000")
Exemplo n.º 2
0
    def test_value_types(self, arg_value, proto_value):
        """Test that it supports different types of values."""
        st.beta_color_picker("the label", arg_value)

        c = self.get_delta_from_queue().new_element.color_picker
        self.assertEqual(c.label, "the label")
        self.assertEqual(c.default, proto_value)
Exemplo n.º 3
0
def render_graphics_params() -> Dict:
    font_family_input = st.selectbox(
        "Font family", ("Arial", "Inkfree"))
    # Get the path to the font chosen by the user
    font_family = choose_font(font_family_input)
    font_size_header = int(st.text_input("Font size", "250"))
    graphic_width = int(st.text_input("Graphic width (pixels)", "1920"))
    graphic_height = int(st.text_input("Graphic height (pixels)", "1080"))
    size = [graphic_width, graphic_height]

    background_color = st.beta_color_picker("Background color", "#060F56")
    transparency = float(st.slider(
        "Background transparency (0 is completely transparent // 1 is completely opaque)", 0.0, 1.0, 1.0))
    text_color = st.beta_color_picker("Text color", "#D4BF2D")
    rgba_bg = hex_to_rgba(background_color, transparency)
    color_scheme = [rgba_bg, text_color]

    wrap_limit = int(st.text_input(
        "Maximum number of characters per line", "32"))
    margin_bottom = int(st.text_input(
        "Vertical margin between lines of text (pixels)", "32"))

    return {
        "font_family": font_family,
        "font_size": font_size_header,
        "size": size,
        "color_scheme": color_scheme,
        "wrap_limit": wrap_limit,
        "margin_bottom": margin_bottom
    }
Exemplo n.º 4
0
def main():
    """A Simple Bioinformatics App"""
    st.title('SeExplorer: Sequence Explorer')
    menus = ['Intro', 'DNA Sequence', 'Dotplot', 'About']
    choices = st.sidebar.selectbox("Select Activity", menus)

    if choices == 'Intro':
        st.subheader('Introduction to Bioinformatics')
    elif choices == 'DNA Sequence':
        st.subheader('DNA Sequence Analysis')
        seqfile = st.file_uploader("Upload a FASTA File", type=['fasta', 'fa', 'txt', ])
        if seqfile is not None:
            dna_record = SeqIO.read(seqfile, "fasta")
            # st.write(dna_record)
            seq = dna_record.seq

            details = st.radio('Details', ('Description', 'Sequence'))
            if details == 'Description':
                st.write(dna_record.description)
            elif details == 'Sequence':
                st.write(dna_record.seq)


            # Nucleotide Frequency
            st.subheader('Nucleotide Frequency')
            dna_freq = Counter(seq)
            st.write(dna_freq)

            # Color Picker
            adenine_color = st.beta_color_picker('Adenine Color')
            guanine_color = st.beta_color_picker('Guanine Color')
            thymine_color = st.beta_color_picker('Thymine Color')
            cytosil_color = st.beta_color_picker('Cytosil Color')

            # Frequency Plotting
            if st.button('Plot Frequency'):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[0].set_color(adenine_color)
                barlist[1].set_color(guanine_color)
                barlist[2].set_color(thymine_color)
                barlist[3].set_color(cytosil_color)
                st.pyplot()

            st.subheader('DNA Composition')
            gc = GC(seq)
            st.write("gc)




    elif choices == 'DotPlot':
        st.subheader('Generate DotPlot for Two Sequences')
    elif choices == 'About':
        st.subheader('About App')
Exemplo n.º 5
0
def main():
    """Simple Bioinformatics App. """

    st.title("Simple Bioinformatics App")
    menu = ["Intro", "DNA", "Dot Plot", "About"]
    choices = st.sidebar.selectbox("Select Activity", menu)

    if choices == "Intro":
        st.subheader("Intro to Bioinformatics")

    elif choices == "DNA":
        st.subheader("DNA Sequence Analysis")

        seq_file = st.file_uploader("FASTA File Upload", type=["fasta", "fa"])

        if seq_file is not None:
            record = SeqIO.read(seq_file, "fasta")

            full_seq = record.seq
            file_details = st.radio("Details", ("Description", "Sequence"))

            if file_details == "Description":
                st.write(record.description)
            elif file_details == "Sequence":
                st.write(full_seq)

            #Nucleotide occurances
            st.subheader("Nucleotide Frequency")
            full_seq_freq = OrderedDict(Counter(full_seq))
            st.write(full_seq_freq)

            bar1_colour = st.beta_color_picker("Pick Colour for Bar 1")
            bar2_colour = st.beta_color_picker("Pick Colour for Bar 2")
            bar3_colour = st.beta_color_picker("Pick Colour for Bar 3")
            bar4_colour = st.beta_color_picker("Pick Colour for Bar 4")

            if st.button("Plot Freq"):
                barlist = plt.bar(full_seq_freq.keys(), full_seq_freq.values())
                barlist[0].set_color(bar1_colour)
                barlist[1].set_color(bar2_colour)
                barlist[2].set_color(bar3_colour)
                barlist[3].set_color(bar4_colour)
                st.pyplot()

            st.subheader("DNA Composition")
            gc_count = full_seq.gc_content()

    elif choices == "Dot Plot":
        st.subheader("Dot Plot Generator")

    else:
        st.subheader("About")
Exemplo n.º 6
0
def write():
    @st.cache(allow_output_mutation=True)
    def load_data():
        data = pd.read_csv("data_final_hsl_cat_weekly.csv")
        data.drop(columns='Unnamed: 0', inplace=True)

        return data

    hue_value = [0, 60, 120, 180, 240, 300]
    satuation_value = [10, 30, 50, 70, 90]
    lightness_value = [10, 30, 50, 70, 90]
    hue = [[330, 30], [30, 90], [90, 150], [150, 210], [210, 270], [270, 330]]
    satuation = [[0, 20], [20, 40], [40, 60], [60, 80], [80, 100]]
    lightness = [[0, 20], [20, 40], [40, 60], [60, 80], [80, 100]]
    hue_name = ['Red', 'Yellow', 'Green', 'Cyan', 'Blue', 'Magenta']

    data = load_data()

    color = st.beta_color_picker('Pick A Color', '#2b82b5')
    color_rgb = hex2rgb(color)
    color_hsl = rgb2hsl(color_rgb)
    pix_h, pix_s, pix_l = hsl2bucket(color_hsl)
    #print(lightness[pix_l])
    color_bucket = 'Hue = ' + hue_name[pix_h] + ', Saturation = ' + str(
        satuation[pix_s]) + ', Lightness = ' + str(lightness[pix_l])
    st.write('The current color belongs to HSL bucket: ' + color_bucket)

    st.plotly_chart(get_plotly_H('h' + str(pix_h), data))

    st.plotly_chart(get_plotly_SxL('s' + str(pix_s) + 'l' + str(pix_l), data))
Exemplo n.º 7
0
def view():
    # Select state
    states = os.listdir(STATES_FOLDER)
    first_state = st.selectbox("Select First State", states)
    second_state = st.selectbox("Select Second State", states)

    # select county
    first_county = st.selectbox("Select First County", get_county(first_state))
    second_county = st.selectbox("Select Second County",
                                 get_county(second_state))

    if first_county == second_county:
        st.error("Please select different counties!!")
        st.stop()

    font = st.selectbox("Select Font", fonts())

    bg_color = st.beta_color_picker("Background color", "#496D89")
    st.write("The current  background color is", bg_color)

    text_color = st.beta_color_picker("Text color", "#FFFFFF")
    st.write("The current text color is", text_color)

    chart = st.selectbox("Chart Types", ChartTypes.list())

    first_county_info = CountyInfo(first_county, first_state, bg_color,
                                   text_color, font, chart)
    second_county_info = CountyInfo(second_county, second_state, bg_color,
                                    text_color, font, chart)

    first_county_police_data, first_county_budget_df = first_county_info.get_data(
    )
    second_county_police_data, second_county_budget_df = second_county_info.get_data(
    )

    st.write(first_county_budget_df)
    st.write(second_county_budget_df)

    st.image(first_county_info.get_budget_for_year(), use_column_width=True)
    st.image(second_county_info.get_budget_for_year(), use_column_width=True)

    first_county_info.chart_display()
    second_county_info.chart_display()
Exemplo n.º 8
0
def render_tweet_graphics_params() -> Dict:
    font_family_input = st.selectbox("Font family", ("Arial",))
    # Get the path to the font chosen by the user
    font_family = choose_font(font_family_input)

    font_size_header = int(st.text_input("Font size (header)", "80"))
    font_size_text = int(st.text_input("Font size (text)", "100"))
    graphic_width = int(st.text_input("Graphic width (pixels)", "1800"))
    graphic_height = int(st.text_input("Graphic height (pixels)", "1800"))
    size = [graphic_width, graphic_height]

    st.write(
        "You can ignore the profile picture dimensions if you won't include a profile picture")
    prof_pic_width = int(st.text_input(
        "Profile picture width for the graphic (pixels)", "0"))
    prof_pic_height = int(st.text_input(
        "Profile picture height for the graphic (pixels)", "0"))
    profile_pic_size = [prof_pic_width, prof_pic_height]

    background_color = st.beta_color_picker("Background color", "#000000")
    transparency = float(st.slider(
        "Background transparency (0 is completely transparent // 1 is completely opaque)", 0.0, 1.0, 1.0))
    text_color = st.beta_color_picker("Text color", "#f0f0f0")
    rgba_bg = hex_to_rgba(background_color, transparency)
    color_scheme = [rgba_bg, text_color]

    wrap_limit = int(st.text_input(
        "Maximum number of characters per line", "32"))
    margin_bottom = int(st.text_input(
        "Vertical margin between lines of text (pixels)", "32"))

    return {
        "font_family": font_family,
        "font_size_text": font_size_text,
        "font_size_header": font_size_header,
        "size": size,
        "profile_pic_size": profile_pic_size,
        "color_scheme": color_scheme,
        "wrap_limit": wrap_limit,
        "margin_bottom": margin_bottom
    }
Exemplo n.º 9
0
def mode_b():
    st.title('Mode B')

    raw_text = st.text_input('Text', 'D3lab')
    times = st.number_input('Multiple times', min_value=0, value=0)

    styles = st.multiselect('Choose Style', ['header', 'bold', 'color'])

    text = raw_text * times
    if 'bold' in styles:
        text = f'**{text}**'
    if 'color' in styles:
        color = st.beta_color_picker('Pick A Color', '#00f900')
        text = f'<span style="color: {color}">{text}</span>'
    if 'header' in styles:
        text = f'## {text}'

    st.markdown(text, unsafe_allow_html=True)
def run_home_page():
    df = load_data("data/thanksgiving_in_multi_lang.csv")
    # st.dataframe(df)

    with st.beta_expander("Happy Thanksgiving Day", expanded=True):
        day_text = " ".join(df['Day'].tolist())
        mywordcloud = WordCloud().generate(day_text)
        fig = plt.figure()
        plt.imshow(mywordcloud, interpolation='bilinear')
        plt.axis('off')
        st.pyplot(fig)

    lang_list = df['Language'].unique().tolist()
    lang_choice = st.sidebar.selectbox("Lang", lang_list)

    if lang_choice:
        thank_word = df[df["Language"] == lang_choice].iloc[0].Word
        thank_day = df[df["Language"] == lang_choice].iloc[0].Day
        st.info("How to Say Happy Thanksgiving in {}".format(lang_choice))
        st.write({"lang": lang_choice, "word": thank_word, "day": thank_day})

    name = st.text_input("Name", "Streamlit")
    bgcolor = st.beta_color_picker("")
    modified_name = "From {0} {0} {0}".format(name)
    updated_text = []
    updated_text.append(modified_name)
    updated_text.extend(df['Word'].tolist())
    # st.write(updated_text)
    new_text = " ".join(updated_text)

    with st.beta_expander("Thanksgiving From {}".format(name)):

        mywordcloud = WordCloud(background_color=bgcolor).generate(new_text)
        fig = plt.figure()
        plt.imshow(mywordcloud, interpolation='bilinear')
        plt.axis('off')
        st.pyplot(fig)
Exemplo n.º 11
0
def complete_tasks(full_seq, des, unique_key):
    file_details = st.radio("Details", ("Description", "Sequence"),
                            key=unique_key)

    #Show description and sequence in DNA Analysis section
    if file_details == "Description":
        st.write(des)
    elif file_details == "Sequence":
        st.write(full_seq)

    #Nucleotide occurances plot and color selector for the bars
    st.subheader("Plot Nucleotide Frequency")
    full_seq_freq = OrderedDict(Counter(full_seq))

    bar1_colour = st.beta_color_picker("Pick Colour for Bar 1", key=unique_key)
    bar2_colour = st.beta_color_picker("Pick Colour for Bar 2", key=unique_key)
    bar3_colour = st.beta_color_picker("Pick Colour for Bar 3", key=unique_key)
    bar4_colour = st.beta_color_picker("Pick Colour for Bar 4", key=unique_key)

    if st.button("Plot Frequency", key=unique_key):
        barlist = plt.bar(full_seq_freq.keys(), full_seq_freq.values())
        barlist[0].set_color(bar1_colour)
        barlist[1].set_color(bar2_colour)
        barlist[2].set_color(bar3_colour)
        barlist[3].set_color(bar4_colour)
        st.pyplot()

    st.subheader("Properties")

    #GC Content, GC Melting temp, GC_skew, Complement and reverse complement
    gc_count = GC(full_seq)
    st.write("GC Content: {}".format(gc_count))

    mt = MeltingTemp.Tm_GC(full_seq, strict=False)
    st.write("Melting Temperature based on GC Content: {}".format(mt))

    gc_skew_bases = st.number_input("Enter number of bases", key=unique_key)
    try:
        gc_skew = GC_skew(full_seq, int(gc_skew_bases))
        st.write("GC Skew for {} bases: {}".format(gc_skew_bases, gc_skew))
    except ValueError:
        st.write("Enter a Valid Number for bases")

    if st.checkbox("Complement", key=unique_key):
        st.write(full_seq.complement())

    elif st.checkbox("Reverse Complement", key=unique_key):
        st.write(full_seq.reverse_complement())

    #Protein Synthesis
    st.subheader("Protein Synthesis")
    p1 = full_seq.translate()
    if st.checkbox("Transcription: DNA to mRNA", key=unique_key):
        st.write(full_seq.transcribe())

    elif st.checkbox("Translation: DNA to 1 letter Amino Acid Sequence",
                     key=unique_key):
        st.write(p1)

    elif st.checkbox("Translation: DNA to 3 letter Amino Acid Sequence",
                     key=unique_key):
        full_aa_name = str(p1).replace("*", "")
        st.write(seq3(full_aa_name))

    elif st.checkbox("Plot Amino Acid Frequency", key=unique_key):
        aa_freq = OrderedDict(Counter(str(p1)))
        bar_colour = st.beta_color_picker("Pick Colour for all Bars",
                                          key=unique_key)
        plt.bar(aa_freq.keys(), aa_freq.values(), color=bar_colour)
        st.pyplot()
        st.write("Asterisk (*) - Denotes Stop Codons.")
Exemplo n.º 12
0
def main():
    image = Image.open('b2.png')
    st.image(image, width=200)
    st.title("Trisakti Bioinformatics Application")
    st.title("Powered by Python")

    menu = ["Intro", "DNA Sequence", "DotPlot", "About"]
    choice = st.sidebar.selectbox("Select Activity", menu)

    if choice == "Intro":
        st.subheader("Intro to BioInformatics")
        image = Image.open('dna.png')
        st.image(image, width=800)

        st.subheader("Bioinformatics")
        st.subheader(
            "Bioinformatika adalah ilmu yang mempelajari penerapan teknik komputasional untuk mengelola dan menganalisis informasi biologis. Bidang ini mencakup penerapan metode matematika, statistika, dan informatika untuk memecahkan masalah-masalah biologis, terutama dengan menggunakan sekuens DNA dan asam amino serta informasi yang berkaitan dengannya. Contoh topik utama bidang ini meliputi basis data untuk mengelola informasi biologis, penyejajaran sekuens (sequence alignment), prediksi struktur untuk meramalkan bentuk struktur protein maupun struktur sekunder RNA, analisis filogenetik, dan analisis ekspresi gen"
        )

        st.subheader("DNA")
        st.subheader(
            "Asam deoksiribonukleat, lebih dikenal dengan singkatan DNA (bahasa Inggris: deoxyribonucleic acid), adalah sejenis biomolekul yang menyimpan dan menyandi instruksi-instruksi genetika setiap organisme dan banyak jenis virus. Instruksi-instruksi genetika ini berperan penting dalam pertumbuhan, perkembangan, dan fungsi organisme dan virus. DNA merupakan asam nukleat; bersamaan dengan protein dan karbohidrat, asam nukleat adalah makromolekul esensial bagi seluruh makhluk hidup yang diketahui. Kebanyakan molekul DNA terdiri dari dua unting biopolimer yang berpilin satu sama lainnya membentuk heliks ganda. Dua unting DNA ini dikenal sebagai polinukleotida karena keduanya terdiri dari satuan-satuan molekul yang disebut nukleotida. Tiap-tiap nukleotida terdiri atas salah satu jenis basa nitrogen (guanina (G), adenina (A), timina (T), atau sitosina (C)), gula monosakarida yang disebut deoksiribosa, dan gugus fosfat. Nukleotida-nukelotida ini kemudian tersambung dalam satu rantai ikatan kovalen antara gula satu nukleotida dengan fosfat nukelotida lainnya. Hasilnya adalah rantai punggung gula-fosfat yang berselang-seling. Menurut kaidah pasangan basa (A dengan T dan C dengan G), ikatan hidrogen mengikat basa-basa dari kedua unting polinukleotida membentuk DNA unting ganda."
        )

    elif choice == "DNA Sequence":
        st.subheader("DNA Sequence Analysis")

        seq_file = st.file_uploader("Upload FASTA File",
                                    type=["fasta", "fa", "txt"])

        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            #st.write(dna_record)
            dna_seq = dna_record.seq

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record.description)
            elif details == "Sequence":
                st.write(dna_record.seq)

            # Frekuensi Nucleotide
            st.subheader("Nucleotide Frequency")
            dna_freq = Counter(dna_seq)
            st.write(dna_freq)
            adenine_color = st.beta_color_picker("Adenine Color")
            thymine_color = st.beta_color_picker("Thymine Color")
            guanine_color = st.beta_color_picker("Guanine Color")
            cytosil_color = st.beta_color_picker("Cytosil Color")

            if st.button("Plot Frequency"):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[2].set_color(adenine_color)
                barlist[3].set_color(thymine_color)
                barlist[1].set_color(guanine_color)
                barlist[0].set_color(cytosil_color)

                st.pyplot()

            st.subheader("DNA Composition")
            gc_score = utils.gc_content(str(dna_seq))
            at_score = utils.at_content(str(dna_seq))
            st.json({"GC Content": gc_score, "AT Content": at_score})

            # Count Nucleotide
            nt_count = st.text_input("Enter Nucleotide",
                                     "Type Nucleotide Alphabet")
            st.write("Number of {} Nucleotide is ::{}".format(
                (nt_count),
                str(dna_seq).count(nt_count)))

            # Protein Synthesis
            st.subheader("Protein Synthesis")
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))

            if st.checkbox("Transcription"):
                st.write(dna_seq.transcribe())

            elif st.checkbox("Translation"):
                st.write(dna_seq.translate())

            elif st.checkbox("Complement"):
                st.write(dna_seq.complement())

            elif st.checkbox("AA Frequency"):
                st.write(aa_freq)

            elif st.checkbox("Plot AA Frequency"):
                aa_color = st.beta_color_picker("Pick An Amino Acid Color")
                #barlist = plt.bar(aa_freq.keys(),aa_freq.values())
                #barlist[2].set_color(aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values(), color=aa_color)
                st.pyplot()

            elif st.checkbox("Full Amino Acid Name"):
                aa_name = str(p1).replace("*", "")
                aa3 = utils.convert_1to3(aa_name)
                st.write(aa_name)
                st.write("=========================")
                st.write(aa3)

                st.write("=========================")
                st.write(utils.get_acid_name(aa3))

    elif choice == "DotPlot":
        st.subheader("Generate Dot Plot For Two Sequences")
        seq_file1 = st.file_uploader("Upload 1st FASTA File",
                                     type=["fasta", "fa"])
        seq_file2 = st.file_uploader("Upload 2nd FASTA File",
                                     type=["fasta", "fa"])

        if seq_file1 and seq_file2 is not None:
            dna_record1 = SeqIO.read(seq_file1, "fasta")
            dna_record2 = SeqIO.read(seq_file2, "fasta")
            # st.write(dna_record)
            dna_seq1 = dna_record1.seq
            dna_seq2 = dna_record2.seq
            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record1.description)
                st.write("=====================")
                st.write(dna_record2.description)
            elif details == "Sequence":
                st.write(dna_record1.seq)
                st.write("=====================")
                st.write(dna_record2.seq)
            cus_limit = st.number_input("Select Max number of Nucleotide", 100,
                                        40000, 10000)
            if st.button("Dot Plot"):
                st.write(
                    "Comparing the first {} Nucleotide of the Two Sequences".
                    format(cus_limit))
                dotplotx(dna_seq1[0:cus_limit], dna_seq2[0:cus_limit])

                st.pyplot()
            elif st.button("Similarity"):
                st.write(
                    "Similarity of Comparing the first {} Nucleotide of the Two Sequences"
                    .format(cus_limit))
                r = pairwise2.align.globalxx(dna_seq1[0:cus_limit],
                                             dna_seq2[0:cus_limit],
                                             one_alignment_only=True,
                                             score_only=True)
                r / len(dna_seq1[0:cus_limit]) * 100

    elif choice == "About":
        st.subheader(
            "Website ini dalam tahap pengembangan & digunakan untuk project penelitian."
        )
        st.subheader("contact : hafiz065001600009.trisakti.ac.id")
Exemplo n.º 13
0
        month = st.slider("Month", min(df["Month"]), max(df["Month"]))

        df_map = df[(df["Year"] == year) & (df["Month"] == month)]

        st.dataframe(df_map)

    if explain:
        st.write("""
Now, let's make a color_picker widget, to choose what color the spikes should be.
We will pass that into the `redefine` param of `observable()`, as well as the value 
of `df_map` (which we will filter + tranform before passing it in, to match the schema
the underlying notebook is expecting).
""")

    with st.echo():
        color = st.beta_color_picker("Spike Color", "#ff0000")

        observable("Spike Chart of Births by County",
                   notebook="d/1f434ef3b0569a00",
                   targets=["chart"],
                   redefine={
                       "rawData":
                       df_map[["countyBirths", "State",
                               "County"]].to_numpy().tolist(),
                       "color":
                       color
                   })

    if explain:
        st.write(
            'Now try changing the "Month" slider and the "Spike Color" color picker, and see how the map responds!'
Exemplo n.º 14
0
def main():
    st.title("Bioinformatics App")
    st.set_option('deprecation.showfileUploaderEncoding', False)

    activity = [
        'Intro', 'SequenceAnalysis', 'DotPlot', 'ProteinSearch',
        "MoleculeVisualizer", "ChemicalSearch"
    ]
    choice = st.sidebar.selectbox("Select Activity", activity)
    if choice == 'Intro':
        st.subheader("Intro")
        st.write(
            """ This is a bioinformatics web app made with Python and Streamlit. Use the left panel dropdown to choose the various features to use."""
        )
        image = Image.open("overviewpicture.png")
        st.image(image, use_column_width=True)

    elif choice == "SequenceAnalysis":
        st.subheader("DNA Sequence Analysis")

        seq_file = st.file_uploader("Upload FASTA File", type=["fasta", "fa"])

        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            # st.write(dna_record)
            dna_seq = dna_record.seq

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record.description)
            elif details == "Sequence":
                st.write(dna_record.seq)

            # Nucleotide Frequencies
            st.subheader("Nucleotide Frequency")
            dna_freq = Counter(dna_seq)
            st.write(dna_freq)
            adenine_color = st.beta_color_picker("Adenine Color")
            thymine_color = st.beta_color_picker("thymine Color")
            guanine_color = st.beta_color_picker("Guanine Color")
            cytosil_color = st.beta_color_picker("cytosil Color")

            if st.button("Plot Freq"):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[2].set_color(adenine_color)
                barlist[3].set_color(thymine_color)
                barlist[1].set_color(guanine_color)
                barlist[0].set_color(cytosil_color)

                st.pyplot()

            st.subheader("DNA Composition")
            gc_score = utils.gc_content(str(dna_seq))
            at_score = utils.at_content(str(dna_seq))
            st.json({"GC Content": gc_score, "AT Content": at_score})

            # Nucleotide Count
            nt_count = st.text_input("Enter Nucleotide Here",
                                     "Type Nucleotide Alphabet")
            st.write("Number of {} Nucleotide is ::{}".format(
                (nt_count),
                str(dna_seq).count(nt_count)))

            # Protein Synthesis
            st.subheader("Protein Synthesis")
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))

            if st.checkbox("Transcription"):
                st.write(dna_seq.transcribe())

            elif st.checkbox("Translation"):
                st.write(dna_seq.translate())

            elif st.checkbox("Complement"):
                st.write(dna_seq.complement())

            elif st.checkbox("AA Frequency"):
                st.write(aa_freq)

            elif st.checkbox("Plot AA Frequency"):
                aa_color = st.beta_color_picker("Pick An Amino Acid Color")
                # barlist = plt.bar(aa_freq.keys(),aa_freq.values(),color=aa_color)
                # barlist[2].set_color(aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values(), color=aa_color)
                st.pyplot()

            elif st.checkbox("Full Amino Acid Name"):
                aa_name = str(p1).replace("*", "")
                aa3 = utils.convert_1to3(aa_name)
                st.write(aa_name)
                st.write("=====================")
                st.write(aa3)

                st.write("=====================")
                st.write(utils.get_acid_name(aa3))

    elif choice == "ProteinSearch":
        st.subheader("Search for Papers Related to a Protein")
        st.write(""" Try entering ACE2 and coronavirus!""")

        ace2 = st.text_input("Query Protein")
        disease = st.text_input(
            "Query Specifier (more specific thing to narrow down papers with)")

        if ace2 and disease is not None:
            protein = req.get(
                'https://www.ebi.ac.uk/proteins/api/proteins?offset=0&size=10&gene='
                + ace2 + '&organism=h**o%20sapiens',
                headers={'Accept': "application/json"})
            for i, v in enumerate(protein.json()[0]['references']):
                counter = 1
                try:
                    title = protein.json(
                    )[0]['references'][i]['citation']['title']
                    if counter == 10:
                        break

                    if title.find(disease) != -1:
                        st.write(title)
                        counter += 1
                except:
                    pass

    elif choice == "DotPlot":
        st.subheader("Generate Dot Plot For Two Sequences")
        seq_file1 = st.file_uploader("Upload 1st FASTA File",
                                     type=["fasta", "fa"])
        seq_file2 = st.file_uploader("Upload 2nd FASTA File",
                                     type=["fasta", "fa"])

        if seq_file1 and seq_file2 is not None:
            dna_record1 = SeqIO.read(seq_file1, "fasta")
            dna_record2 = SeqIO.read(seq_file2, "fasta")
            # st.write(dna_record)
            dna_seq1 = dna_record1.seq
            dna_seq2 = dna_record2.seq

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record1.description)
                st.write("=====================")
                st.write(dna_record2.description)
            elif details == "Sequence":
                st.write(dna_record1.seq)
                st.write("=====================")
                st.write(dna_record2.seq)

            cus_limit = st.number_input("Select Max number of Nucleotide", 10,
                                        200, 50)
            if st.button("Dot Plot"):
                st.write(
                    "Comparing the first {} Nucleotide of the Two Sequences".
                    format(cus_limit))
                dotplotx(dna_seq1[0:cus_limit], dna_seq2[0:cus_limit])

                st.pyplot()

    elif choice == "MoleculeVisualizer":
        st.subheader(
            "Look at a molecule! Pre-loaded example is the Covid-19 Spike Protein. Thank you to: https://github.com/napoles-uach/streamlit_3dmol"
        )

        component_3dmol()

    elif choice == "ChemicalSearch":
        st.title(
            "Search for chemicals and get info. Pre-loaded example: imatinib")
        user_compound = st.text_input("Enter compound name", 'imatinib')
        if user_compound is not None:
            results = pcp.get_compounds(user_compound, 'name')
            for compound in results:
                st.write('Compound ID: ' + str(compound.cid))
                st.write('SMILES: ' + compound.isomeric_smiles)

                vioxx = Compound.from_cid(compound.cid)
                st.write('Molecular Formula: ' + vioxx.molecular_formula)
                st.write('Molecular Weight: ' + str(vioxx.molecular_weight))
                st.write('IUPAC Name: ' + vioxx.iupac_name)
                st.write('xlogp value: ' + str(vioxx.xlogp))
Exemplo n.º 15
0
def main():

    st.title("Bioinformatik Uygulaması")

    st.sidebar.header("Lütfen Seçim Yapınız")
    secenekler = ["Giriş","DNA Sekansı", "Çoklu Sekans Hizalama", "Sekans Puanlaması", "Hedef Protein Analizi", "Protein Çözünürlüğü"]
    select_box = st.sidebar.selectbox("Yapmak istediğiniz işlem: ", secenekler)

    if select_box == "Giriş":
        st.header("Burası giriş sayfasıdır")
        st.text("")
        st.write("Buraya site hakkında genel bilgilendirmeler girilecektir.")
        st.write("lorem ipsum dolor.")
    elif select_box == "DNA Sekansı":
        st.subheader("DNA Sekans Analizi")

        st.warning("Lütfen DNA Sekansınızı sol taraftaki barda bulunan dosya yükleme kısmından içeri aktarınız.")

        seq_dosya = st.sidebar.file_uploader("Lütfen FASTA yapılı dosyanızı girin", type=["FASTA","fa"])
        
        if seq_dosya is not None:
            dna = SeqIO.read(seq_dosya, "fasta")
            st.write(dna)

            dna_sekansi = dna.seq

            details = st.radio("Detaylar", ("Açıklama", "Sekansı Göster"))
            if details == "Açıklama":
                st.text("")
                st.write(dna.description)
            elif details == "Sekansı Göster":
                st.text("")
                st.write(dna.seq)

            st.text("")
            st.text("")

            st.subheader("Nükleotid bilgisi")

            st.text("")


            if ("M" and "L") in str(dna_sekansi):
                st.write("Nükleotid bilgilerinin hesaplanabilmesi için lütfen bir **DNA sekansı** giriniz!")
                

            else:
                
                adenin = int(str(dna_sekansi).count("A"))
                guanin = int(str(dna_sekansi).count("G"))
                citosin = int(str(dna_sekansi).count("C"))
                timin = int(str(dna_sekansi).count("T"))
                st.write("**Adenin** sayısı = {0} ".format(adenin))
                st.write("**Timin** sayısı = {0} ".format(timin))
                st.write("**Guanin** sayısı = {0} ".format(guanin))
                st.write("**Sitozin** sayısı = {0} ".format(citosin))

                st.text("")
                st.text("")

                if st.checkbox("Grafik üzerinde göster"):
                    adenin_color = st.beta_color_picker('Adenin için renk seçin', "#F50000")
                    timin_color = st.beta_color_picker('Timin için renk seçin', "#00DE2D")
                    guanin_color = st.beta_color_picker('Guanin için renk seçin', "#1A00FF")
                    sitozin_color = st.beta_color_picker('Sitozin için renk seçin', "#000000")
                    
                    numbers = [adenin, timin, guanin, citosin]
                    plot(numbers, adenin_color, timin_color, guanin_color, sitozin_color)
                
                st.text("")

                st.subheader("İçerik oranları")
                st.text("")

                gc_orani = round(gc_content(dna_sekansi), 2)
                at_orani = round(at_content(dna_sekansi),2)

                st.write("**GC** oranı = % {0}".format(gc_orani))
                st.write("**AT** oranı = % {0}".format(at_orani))

                st.text("")

                st.subheader("Protein Sentezi")
                aa = dna_sekansi.translate()
                aa_frekansi = Counter(str(aa))
                st.text("")

                if st.button("Translasyon Tablosunu Görmek için Tıklayınız"):
                    standard_table = CodonTable.unambiguous_dna_by_name["Standard"]
                    st.text(standard_table)
                
                st.text("")

                if st.checkbox("Transkripsiyon"):
                    transkribe = dna_sekansi.transcribe()
                    st.write(transkribe)
                elif st.checkbox("Translasyon"):
                    transle = dna_sekansi.translate()
                    st.write(transle)
                elif st.checkbox("Complement"):
                    st.write(dna_sekansi.complement())
                elif st.checkbox("Amino Asit Sıklığı"):
                    st.write(aa_frekansi)
                elif st.checkbox("Amino Asit Grafiği"):
                    st.text("")
                    aa_color = st.beta_color_picker("Buradan Renk Değiştirebilirsin")
                    plt.bar(aa_frekansi.keys(), aa_frekansi.values(), color = aa_color)
                    st.pyplot()
                elif st.checkbox("Tam Amino Asit İsimleri"):
                    st.text("")
                    aa_ismi = str(aa).replace("*", "")
                    aa3 = utils.convert_1to3(aa_ismi)
                    st.write("**Harf Gösterimi**")
                    st.text(aa_ismi)
                    st.write("**************************************")
                    st.write("**Kısaltma Gösterimi**")
                    st.text(aa3)
                    st.write("**************************************")
                    st.write("**Açık İsim Gösterimi**")
                    st.text(utils.get_acid_name(aa3))              

    elif select_box == "Çoklu Sekans Hizalama":

        st.warning("Lütfen karşılaştırma yapacağınız sekansları sol taraftaki barda bulunan dosya yükleme kısmından içeri aktarınız.")
        seq1 = st.sidebar.file_uploader("1.FASTA dosyanızı giriniz", type=["fasta", "fa"])

        seq2 = st.sidebar.file_uploader("2.FASTA dosyanızı giriniz", type=["fasta", "fa"])

        if seq1 and seq2 is not None:
            sekans1 = SeqIO.read(seq1, "fasta")
            sekans2 = SeqIO.read(seq2, "fasta")

            st.text("")

            st.write("**1.Sekans** = {0}".format(sekans1.description))
            st.text("")
            st.write("**2.Sekans** = {0}".format(sekans2.description))
            st.text("")
            st.write("**Hizalanmış Durum:**")

            alignments = pairwise2.align.globalxx(sekans1.seq, sekans2.seq)
            st.text(pairwise2.format_alignment(*alignments[0]))
            st.text("")

            if st.checkbox("BLOSUM62 Puanlamasını Görmek için tıklayınız"):

                secenek = st.radio("Seçenekler",("Hizalanmış Sekans Gösterimi","Tüm Sekans Gösterimi"))

                if secenek == "Hizalanmış Sekans Gösterimi":

                    blosum62 = substitution_matrices.load("BLOSUM62")
                    alignment_blossum = pairwise2.align.localds(sekans1.seq, sekans2.seq, blosum62, -10, -1)
                    st.text(pairwise2.format_alignment(*alignment_blossum[0]))
                    
                elif secenek == "Tüm Sekans Gösterimi":
                    blosum62_2 = substitution_matrices.load("BLOSUM62")
                    full_alignment_blossum = pairwise2.align.localds(sekans1.seq, sekans2.seq, blosum62_2, -10, -1)
                    st.text(pairwise2.format_alignment(*full_alignment_blossum[0], full_sequences=True))

                  #Bu kısımda geliştirme olarak gap-penalty ve gap-extension gibi değerleri kullanıcının değiştirebileceği gibi ayarlayabiliriz. 
                  #Geliştirme olarak sekansları taşımak yerine yazılabilir hale de getirebilirim!!!!!

    elif select_box == "Sekans Puanlaması":

        
        st.text("")
        st.text("")
        st.text("")
        st.subheader("Kendi Hesaplamanızı Yapın:")
        
        seq1_puan = st.text_area("1.Sekans")
        seq2_puan = st.text_area("2.Sekans")
        substitution_matrices.load()
        option = st.selectbox('Kullanmak İstediğiniz Matrix?',("BENNER22", 'BENNER6', 'BENNER74', 'BLOSUM45', 'BLOSUM50', 'BLOSUM62', 'BLOSUM80', 'BLOSUM90', 'DAYHOFF', 'FENG', 'GENETIC', 'GONNET1992', 'JOHNSON', 'JONES', 'LEVIN', 'MCLACHLAN', 'MDM78', 'NUC.4.4', 'PAM250', 'PAM30', 'PAM70', 'RAO', 'RISLER', 'SCHNEIDER', 'STR'))
        st.write('Seçtiğiniz Matrix:', option)
        try:        
            aligner = Align.PairwiseAligner()
            if option == "BENNER22":
                matrix = substitution_matrices.load("BENNER22")
                st.text(matrix)
                aligner.substitution_matrix = matrix
                score = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score)) 
            elif option == "BLOSUM62":
                matrix2 = substitution_matrices.load("BLOSUM62")
                st.text(matrix2)
                aligner.substitution_matrix = matrix2
                score2 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score2))
            elif option == "BENNER6":
                matrix3 = substitution_matrices.load("BENNER6")
                st.text(matrix3)
                aligner.substitution_matrix = matrix3
                score3 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score3))
            elif option == "BENNER74":
                matrix4 = substitution_matrices.load("BENNER74")
                st.text(matrix4)
                aligner.substitution_matrix = matrix4
                score4 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score4))
            elif option == "BLOSUM45":
                matrix5 = substitution_matrices.load("BLOSUM45")
                st.text(matrix5)
                aligner.substitution_matrix = matrix5
                score5 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score5))
            elif option == "BLOSUM50":
                matrix6 = substitution_matrices.load("BLOSUM50")
                st.text(matrix6)
                aligner.substitution_matrix = matrix6
                score6 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score6))
            elif option == "BLOSUM80":
                matrix7 = substitution_matrices.load("BLOSUM80")
                st.text(matrix7)
                aligner.substitution_matrix = matrix7
                score7 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score7))
            elif option == "BLOSUM90":
                matrix8 = substitution_matrices.load("BLOSUM90")
                st.text(matrix8)
                aligner.substitution_matrix = matrix8
                score8 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score8))
            elif option == "DAYHOFF":
                matrix9 = substitution_matrices.load("DAYHOFF")
                st.text(matrix9)
                aligner.substitution_matrix = matrix9
                score9 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score9))
            elif option == "FENG":
                matrix10 = substitution_matrices.load("FENG")
                st.text(matrix10)
                aligner.substitution_matrix = matrix10
                score10 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score10))
            elif option == "GENETIC":
                matrix11 = substitution_matrices.load("GENETIC")
                st.text(matrix11)
                aligner.substitution_matrix = matrix11
                score11 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score11))
            elif option == "GONNET1992":
                matrix12 = substitution_matrices.load("GONNET1992")
                st.text(matrix12)
                aligner.substitution_matrix = matrix12
                score12 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score12))
            elif option == "JOHNSON":
                matrix13 = substitution_matrices.load("JOHNSON")
                st.text(matrix13)
                aligner.substitution_matrix = matrix13
                score13 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score13))
            elif option == "JONES":
                matrix14 = substitution_matrices.load("JONES")
                st.text(matrix14)
                aligner.substitution_matrix = matrix14
                score14 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score14))
            elif option == "LEVIN":
                matrix15 = substitution_matrices.load("LEVIN")
                st.text(matrix15)
                aligner.substitution_matrix = matrix15
                score15 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score15))
            elif option == "MCLACHLAN":
                matrix16 = substitution_matrices.load("MCLACHLAN")
                st.text(matrix16)
                aligner.substitution_matrix = matrix16
                score16 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score16))
            elif option == "MDM78":
                matrix17 = substitution_matrices.load("MDM78")
                st.text(matrix17)
                aligner.substitution_matrix = matrix17
                score17 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score17))
            elif option == "NUC.4.4":
                matrix18 = substitution_matrices.load("NUC.4.4")
                st.text(matrix18)
                aligner.substitution_matrix = matrix18
                score18 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score18))
            elif option == "PAM250":
                matrix19 = substitution_matrices.load("PAM250")
                st.text(matrix19)
                aligner.substitution_matrix = matrix19
                score19 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score19))
            elif option == "PAM30":
                matrix20 = substitution_matrices.load("PAM30")
                st.text(matrix20)
                aligner.substitution_matrix = matrix20
                score20 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score20))
            elif option == "PAM70":
                matrix21 = substitution_matrices.load("PAM70")
                st.text(matrix21)
                aligner.substitution_matrix = matrix21
                score21 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score21))
            elif option == "RAO":
                matrix22 = substitution_matrices.load("RAO")
                st.text(matrix22)
                aligner.substitution_matrix = matrix22
                score22 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score22))
            elif option == "RISLER":
                matrix23 = substitution_matrices.load("RISLER")
                st.text(matrix23)
                aligner.substitution_matrix = matrix23
                score23 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score23))
            elif option == "SCHNEIDER":
                matrix24 = substitution_matrices.load("SCHNEIDER")
                st.text(matrix24)
                aligner.substitution_matrix = matrix24
                score24 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score24))
            elif option == "STR":
                matrix25 = substitution_matrices.load("STR")
                st.text(matrix25)
                aligner.substitution_matrix = matrix25
                score25 = aligner.score(seq1_puan, seq2_puan)
                st.write("**Sekans Puanı** = {0} ".format(score25))
            
            #aligner.substitution_matrix = matrix
            #score = aligner.score("ACDQ", "ACDQ")
            #st.write(score)
        except:
            st.text("")

    elif select_box == "Hedef Protein Analizi":
        try:
            st.text("")
            arama = st.sidebar.text_input("Aramak İstediğiniz Proteini Yazınız.", "coronavirus")
            target = new_client.target
            target_query = target.search(arama) #Your target protein name that you want to search
            targets = pd.DataFrame.from_dict(target_query)
            st.write("**Chembl Verisi**:")
            st.write(targets)
            st.text("")
            
            hedef_protein = st.number_input("İleri araştırma yapmak istediğiniz Single Proteinin solunda yazan numarayı girin.", min_value=0 ,value=4, format="%d")
            selected_target = targets.target_chembl_id[hedef_protein]
            st.text("")
            st.write("Seçtiğiniz proteinin **ChEMBL ID**'si: {0}".format(selected_target))
            activity = new_client.activity
            res = activity.filter(target_chembl_id=selected_target).filter(standard_type="IC50")
            df = pd.DataFrame.from_dict(res)
            
            st.text("")
        except:
            st.warning("Girilen Değer Geçersiz")
        

        if hedef_protein is not None:
            

            if st.checkbox("Seçtiğiniz Proteinin IC50 değerlerine göre elde edilen verisini görüntülemek için tıklayınız."):
                if df.empty:
                    st.warning("Lütfen bir Single Protein seçiniz!")
                else:
                        
                    st.write(df)
                    st.text("")
                
                    st.markdown(download_button(df, 'IC50_Veri.csv', 'CSV Dosyasını Bilgisayarına Yükle'), unsafe_allow_html=True)
            
            
            st.text("")
            st.text("")
            st.markdown("<h3 style='text-align: center; color: red;'>Seçilen Protein için molekül aktivitesini hesaplayan ML programını çalıştırmak isterseniz aşağıda ki butona tıklayınız.</h3>", unsafe_allow_html=True)
            st.text("")
            
            df2 = df[df.standard_value.notna()]
            bioactivity_class = []

            mol_cid = []
            canonical_smiles = []
            standard_value = []
            for unit in df2.standard_value:
                if float(unit) >= 10000:
                    bioactivity_class.append("inactive")
                elif float(unit) <= 1000:
                    bioactivity_class.append("active")
                else:
                    bioactivity_class.append("intermediate")

            for i in df2.molecule_chembl_id:

                mol_cid.append(i)
            
            for i in df2.canonical_smiles:

                canonical_smiles.append(i)
                
            for i in df2.standard_value:

                standard_value.append(i)
                    
                    

            data_tuples = list(zip(mol_cid, canonical_smiles, standard_value, bioactivity_class))
            df3 = pd.DataFrame( data_tuples,  columns=['molecule_chembl_id', 'canonical_smiles', 'standard_value','bioactivity_class' ])
            st.text("")
            if df.empty:
                st.warning("Lütfen bir Single Protein seçiniz!")
            else:
                if st.checkbox("Moleküler Aktivite Hesapla"):
                    st.text("")
                    st.text("")
                    st.write(df3)
                    st.text("")
                    st.markdown(download_button(df3, 'Genel_Veri.csv', 'CSV Dosyasını Bilgisayarına Yükle'), unsafe_allow_html=True)

                    st.text("")
                    if st.selectbox("Yalnızca Aktif Olanları Göster",("Aktif","")):
                        active_data = (df3.loc[df3['bioactivity_class'] == "active"])
                        st.write(active_data)
                        st.text("")
                        st.markdown(download_button(active_data, 'Aktif_Veri.csv', 'CSV Dosyasını Bilgisayarına Yükle'), unsafe_allow_html=True)

            
                st.text("")
                st.text("")
                st.markdown("<h3 style='text-align: center; color: red;'>Lipinski Tanımlayıcılarını Hesaplamak için aşağıdaki butona tıklayınız.</h3>", unsafe_allow_html=True)
                st.text("")
                
                button_sent = st.checkbox("Lipinski Tanımlayıcıları")
                
                if button_sent:
                    session_state.button_sent = True

                if session_state.button_sent:
                    st.subheader("Lipinski Verisi:")
                    st.write("**MW** = Moleküler Ağırlık")
                    st.write("**LogP** = Molekül Çözünürlüğü")
                    st.write("**NumHDonors** = Hidrojen Bağı Vericileri")
                    st.write("**NumHAcceptors** = Hidrojen Bağı Alıcıları")
                    exploratory_data = df3
                    df_lipinski = lipinski(exploratory_data.canonical_smiles)
                    #st.write(df_lipinski)
                    df_combined = pd.concat([exploratory_data,df_lipinski], axis=1)
                    st.subheader("Birleştirilmiş Veri:")
                    st.write(df_combined)
                    st.markdown(download_button(df_combined, 'Birleştirilmiş_Veri.csv', 'CSV Dosyasını Bilgisayarına Yükle'), unsafe_allow_html=True)
                    df_norm = norm_value(df_combined)
                    #st.write(df_norm)
                    df_final = pIC50(df_norm)
                    st.subheader("IC50'nin pIC50'ye dönüştürülmüş halindeki veri seti:")
                    st.write(df_final)
                    st.markdown(download_button(df_final, 'pIC50_Verisi.csv', 'CSV Dosyasını Bilgisayarına Yükle'), unsafe_allow_html=True)
                    df_class = df_final[df_final.bioactivity_class != "intermediate"]

                    def mannwhitney(descriptor, verbose=False):

                        # seed the random number generator
                        seed(1)

                        # actives and inactives
                        selection = [descriptor, 'bioactivity_class']
                        df = df_class[selection]
                        active = df[df.bioactivity_class == 'active']
                        active = active[descriptor]

                        selection = [descriptor, 'bioactivity_class']
                        df = df_class[selection]
                        inactive = df[df.bioactivity_class == 'inactive']
                        inactive = inactive[descriptor]

                        # compare samples
                        stat, p = mannwhitneyu(active, inactive)
                        #print('Statistics=%.3f, p=%.3f' % (stat, p))

                        # interpret
                        alpha = 0.05
                        if p > alpha:
                            interpretation = 'Same distribution (fail to reject H0)'
                        else:
                            interpretation = 'Different distribution (reject H0)'
                        
                        results = pd.DataFrame({'Descriptor':descriptor,
                                                'Statistics':stat,
                                                'p':p,
                                                'alpha':alpha,
                                                'Interpretation':interpretation}, index=[0])
                        filename = 'mannwhitneyu_' + descriptor + '.csv'
                        results.to_csv(filename)

                        return results

                    st.text("")
                    st.text("")
                    session_state.grafik = st.checkbox("Aktif/İnaktif Molekül Grafiği")
                    session_state.mw = st.checkbox("Moleküler Ağırlık/Çözünürlük Grafiği")
                    session_state.pic50 = st.checkbox("pIC50/Moleküler Aktiflik Grafiği")
                    session_state.logp = st.checkbox("Çözünürlük/Moleküler Aktiflik Grafiği")
                    session_state.donors = st.checkbox("Hidrojen Bağı Vericiler/Moleküler Aktiflik Grafiği")
                    session_state.acceptors = st.checkbox("Hidrojen Bağı Alıcılar/Moleküler Aktiflik Grafiği")

                    if session_state.grafik:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**Aktif/İnaktif Molekül Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))

                        #sns.countplot(x='bioactivity_class', data=df_class, edgecolor='black')

                        plt.xlabel('Bioactivity class', fontsize=14, fontweight='bold')
                        plt.ylabel('Frequency', fontsize=14, fontweight='bold')
                        
                        st.pyplot()
                        #st.markdown(get_table_download_link(veri), unsafe_allow_html=True)
                        
                        #Buralara PDF indirici eklenecek

                    if session_state.mw:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**Moleküler Ağırlık/Çözünürlük Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))
                        #sns.scatterplot(x='MW', y='LogP', data=df_class, hue='bioactivity_class', size='pIC50', edgecolor='black', alpha=0.7)

                        plt.xlabel('MW', fontsize=14, fontweight='bold')
                        plt.ylabel('LogP', fontsize=14, fontweight='bold')
                        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
                        st.pyplot()
                        
                        #Buralara PDF indirici eklenecek
                        st.write("**Mann-Whitney U Test Verisi**:")
                        st.write(mannwhitney("MW"))

                    if session_state.pic50:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**pIC50/Moleküler Aktiflik Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))

                        sns.boxplot(x = 'bioactivity_class', y = 'pIC50', data = df_class)

                        plt.xlabel('Bioactivity class', fontsize=14, fontweight='bold')
                        plt.ylabel('pIC50 value', fontsize=14, fontweight='bold')
                        st.pyplot()
                        #Buralara PDF indirici eklenecek

                        st.write("**Mann-Whitney U Test Verisi**:")
                        st.write(mannwhitney("pIC50"))
                    
                    if session_state.logp:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**Çözünürlük/Moleküler Aktiflik Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))

                        sns.boxplot(x = 'bioactivity_class', y = 'LogP', data = df_class)

                        plt.xlabel('Bioactivity class', fontsize=14, fontweight='bold')
                        plt.ylabel('LogP', fontsize=14, fontweight='bold')
                        st.pyplot()
                        #Buralara PDF indirici eklenecek

                        st.write("**Mann-Whitney U Test Verisi**:")
                        st.write(mannwhitney("LogP"))
                    
                    if session_state.donors:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**Hidrojen Bağı Vericiler/Moleküler Aktiflik Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))

                        sns.boxplot(x = 'bioactivity_class', y = 'NumHDonors', data = df_class)

                        plt.xlabel('Bioactivity class', fontsize=14, fontweight='bold')
                        plt.ylabel('NumHDonors', fontsize=14, fontweight='bold')
                        st.pyplot()
                        #Buralara PDF indirici eklenecek

                        st.write("**Mann-Whitney U Test Verisi**:")
                        st.write(mannwhitney("NumHDonors"))

                    if session_state.acceptors:
                        st.write("**********************************")
                        st.text("")
                        st.subheader("**Hidrojen Bağı Alıcılar/Moleküler Aktiflik Grafiği**")

                        plt.figure(figsize=(5.5, 5.5))

                        sns.boxplot(x = 'bioactivity_class', y = 'NumHAcceptors', data = df_class)

                        plt.xlabel('Bioactivity class', fontsize=14, fontweight='bold')
                        plt.ylabel('NumHAcceptors', fontsize=14, fontweight='bold')
                        st.pyplot()
                        #Buralara PDF indirici eklenecek

                        st.write("**Mann-Whitney U Test Verisi**:")
                        st.write(mannwhitney("NumHAcceptors"))


                
            
            

    elif select_box == "Protein Çözünürlüğü":
        pass
Exemplo n.º 16
0
st.write('Your birthday is:', d)
st.write('---')

# 显示时间输入小部件
import datetime
t = st.time_input(
    label='Set an alarm for',
    value=datetime.time(
        8, 45
    )  # (datetime.time/datetime.datetime)–此小部件首次呈现时的值。这将在内部强制转换为str。默认为当前时间。
)
st.write('Alarm is set for', t)
st.write('---')

# 显示文件上传器小部件
# 默认情况下,上传的文件限制为200MB。您可以使用server.maxUploadSize配置选项进行配置。
uploaded_file = st.file_uploader(
    label="Choose a CSV file",  # 向用户说明此文件上传器的用途
    type="csv"  # str或str的列表或None–允许的扩展数组。['png','jpg']默认情况下,允许所有扩展名。
)
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)
st.write('---')

# 显示颜色选择器小部件
color = st.beta_color_picker(
    label='Pick A Color',  # 简短的标签,向用户说明此输入的用途
    value='#00f900'  # (str 或None)–首次渲染时此小部件的十六进制值。如果为无,则默认为黑色。
)
st.write('The current color is', color)
Exemplo n.º 17
0
#File Uploader
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
   data = pd.read_csv(uploaded_file)
   st.write(data)
   st.success("success")
else:
	st.warning("this is a warning: Upload a csv file")
    


st.text("----"*100)
#Color Picker

color = st.beta_color_picker('Pick A Color', '#00f900')
st.write('The current color is', color)


st.text("----"*100)

#Adding Widget to side bar

add_selectbox = st.sidebar.selectbox(
    "What is your favorite course?",
    ("A course from Total Data Science", "Others", "Am not sure")
)


st.text("----"*100)
if radio_button_options == 'A':
    st.write('option A chosen')
elif radio_button_options == 'B':
    st.write('option B chosen')
elif radio_button_options == 'C':
    st.write('option C chosen')

# *** MULTISELECT ***
st.title('Multiselect')
options = st.multiselect('What are your favorite colors',
                         ['green', 'orange', 'red', 'blue', 'purple'])

st.write('You selected:')
for i in options:
    st.write(i)

# *** DATES ***
st.title('Select Dates')
d = st.date_input('select date:', datetime.date(2016, 1, 1))
st.write(d)

# *** COLOR PICKER ***
st.title('Color Picker')
color = st.beta_color_picker('pick a color')
st.write(color)

# *** BALLOONS ***
# st.balloons()

# *** SEE DOCUMENTATION FOR MORE WIDGETS ***
Exemplo n.º 19
0
    st.write('This is a secret!')

with st.beta_expander('Reveal Secret'):
    st.write('Hi!')

choice = st.selectbox("Language", ['Python', 'C', 'Java'])
st.write(f'You have chosen {choice}')

multisel = st.multiselect(
    'Food', ('Indian', 'Chinese', 'South Indian', 'North Indian'),
    default='South Indian')

age = st.slider('Age', 1, 100, 1)
slider = st.select_slider("Choose Slider",
                          options=['A', 'B', 'C', 'D', 'E'],
                          value=('A', 'B'))

#st.image(image_url) or
#from PIL import Image
#st.image(Image.open(local_path), use_column_width = True)

name = st.text_input('Name')
st.info(name)
message = st.text_area('Message', height=100)
st.write(message)
age = st.number_input('Age', 1, 25)  # or 1.0 to 25.0
date = st.date_input('Exam date')
time = st.time_input('Exam time')
pas = st.text_input('Password', type='password')
color = st.beta_color_picker('Select Color')
Exemplo n.º 20
0
#    df2['show_data'])


'*', len(df), "Galaxy Clusters with signal to noise ratio (s/n) larger than ", snr_min, 'and redshift larger than ', z_min, '.'
#'*', "Largest mass among clusters with s/n $\ge$  ", snr_min, ' : ', str(np.round(df['M_sz/1e14'].max(), 2)), r'$\times \ 10^{14}$', r'$M_{\odot}$.'
#'*', "Average mass of clusters with s/n $\ge$  ", snr_min, ' : ', str(np.round(df['M_sz/1e14'].mean(), 2)), r'$\times \ 10^{14}$', r'$M_{\odot}$.'

dfe = df[['z', 'SNR', 'M_sz/1e14', 'Y5R500']]#pd.DataFrame({'z_min': [np.round(df['z'].min(), 2)], 'z_max': [np.round(df['z'].max(), 2)], 'M_max [1e14 M_sol]': [np.round(df['M_sz/1e14'].max(), 2)]},
        #            index = ['s/n > '+str(snr_min)])

#df.style.set_caption("Hello World")
df_desc = dfe.describe()[1:]
st.table(df_desc)

# ======================================================================================================
color = st.beta_color_picker('Pick A Color For Your Map', '#00f900')
if show_map:

    deg = df['GLON']#glon
    deg1 = df['GLAT']

    ra = coord.Angle(deg*u.degree)
    ra = ra.wrap_at(180*u.degree)
    dec = coord.Angle(deg1*u.degree)

    #fig = plt.figure()
    #hp.mollview(np.zeros(hp.nside2npix(6)), min = z.min(), max = z.max())
    #hp.graticule()
    #ax = fig.add_subplot(111, projection = "mollweide")
    #hp.projscatter(glon[np.where(q > snr_min)[0]], glat[np.where(q > snr_min)[0]], lonlat = True, c = z[np.where(q > snr_min)[0]], s = 20, edgecolor = 'k')            # Add grid
    #hp.mollview(np.zeros(hp.nside2npix(6)), cbar = None)
Exemplo n.º 21
0
 def test_invalid_string(self):
     """Tests that when the string doesn't match regex, an exception is generated"""
     with pytest.raises(StreamlitAPIException) as exc_message:
         st.beta_color_picker("the label", "#invalid-string")
Exemplo n.º 22
0
# Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st

c1 = st.beta_color_picker("Default Color")
st.write("Color 1", c1)

c2 = st.beta_color_picker("New Color", "#EB144C")
st.write("Color 2", c2)
def main():

    st.title('Simple Bioinformatics App')
    menu = ["DNA Sequence", "Dot Plot"]
    choice = st.sidebar.selectbox("Select Activity", menu)

    if choice == "DNA Sequence":
        st.subheader("DNA Sequence Analysis")
        seq_file = st.file_uploader("Upload FASTA File", type=["fasta", "fa"])
        #text_io = io.TextIOWrapper(seq_file)

        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            #st.write(dna_record)
            dna_seq = dna_record.seq
            desc = dna_record.description
            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(desc)
            elif details == "Sequence":
                st.write(dna_seq)

            # Nucleotide Frequencies
            st.subheader("Nucleotide Frequencies")
            dna_freq = Counter(dna_seq)
            st.write(dna_freq)
            adenine_color = st.beta_color_picker("Adenine Color")
            guanine_color = st.beta_color_picker("Guanine Color")
            thymine_color = st.beta_color_picker("Thymine Color")
            cytosil_color = st.beta_color_picker("Cytosil Color")

            if st.button("Plot Freq"):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[0].set_color(adenine_color)
                barlist[1].set_color(thymine_color)
                barlist[2].set_color(guanine_color)
                barlist[3].set_color(cytosil_color)

                st.pyplot()

            st.subheader("DNA Composition")
            gc_score = utils.gc_content(str(dna_seq))
            at_score = utils.at_content(str(dna_seq))
            st.json({"GC Content ": gc_score, "AT Content ": at_score})

            # Nucleotide Count
            nt_count = st.text_input("Enter Nucleotide Here",
                                     "Type Nucleotide Alphabet")
            st.write("Number of {} nucleotide is : {} ".format(
                (nt_count),
                str(dna_seq).count(nt_count)))

            # Protein Synthesis
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))

            st.subheader("Protein Synthesis")
            if st.checkbox("Transcription"):
                st.write(dna_seq.transcribe())
            elif st.checkbox("Translation"):
                st.write(dna_seq.translate())
            elif st.checkbox("Complement"):
                st.write(dna_seq.complement())
            elif st.checkbox("AA Frequency"):
                st.write(aa_freq)
            elif st.checkbox("AA Plot Frequency"):
                #aa_color = st.beta_color_picker("Amino Acid Color")
                #barlist = plt.bar(aa_freq.keys(), aa_freq.values(), color = aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values())
                #barlist[0].set_color(aa_color)
                st.pyplot()
            elif st.checkbox("Full Amino Acid Name"):
                aa_name = str(p1).replace("*", "")
                st.write(aa_name)
                st.write("--------------------------")
                st.write(utils.convert_1to3(aa_name))

    elif choice == "Dot Plot":
        st.subheader("Generate Dot Plot For Two Sequences")
        seq_file = st.file_uploader("Upload 1st FASTA File",
                                    type=["fasta", "fa"])
        seq_file2 = st.file_uploader("Upload 2nd FASTA File",
                                     type=["fasta", "fa"])

        # text_io = io.TextIOWrapper(seq_file)

        if seq_file and seq_file2 is not None:
            dna_record1 = SeqIO.read(seq_file, "fasta")
            dna_record2 = SeqIO.read(seq_file2, "fasta")

            # st.write(dna_record)
            dna_seq1 = dna_record1.seq
            dna_seq2 = dna_record2.seq

            desc1 = dna_record1.description
            desc2 = dna_record2.description

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(desc1)
                st.write("----------")
                st.write(desc2)
            elif details == "Sequence":
                st.write(dna_seq1)
                st.write("----------")
                st.write(dna_seq2)

            custom_limit = st.number_input("Select max number of Nucleotide ",
                                           10, 200, 25)
            if st.button("Dot Plot"):
                st.write("Comparing the first {} Nucleotide of Two Sequences ".
                         format(custom_limit))
                dotplotx(dna_seq1[0:custom_limit], dna_seq2[0:custom_limit])
                st.pyplot()
Exemplo n.º 24
0
def main():
    """Bioinformatics Genome analysis web app"""

    st.title(
        "DNA Genome analysis and Cosine Similarity Analysis web application")
    menu = [
        "Introduction", "DNA sequence Analysis", "Dotplot Analysis", "About us"
    ]
    choice = st.sidebar.selectbox("Select Option", menu)

    if choice == "Introduction":
        st.subheader("Welcome to our Sequence Analysis Application :)")
    elif choice == "DNA sequence Analysis":
        st.subheader("DNA sequence Analysis will be done here.")
        seq_file = st.file_uploader(
            "Upload the .FASTA file for any DNA analysis of the considered Genome.",
            type=["fasta", "fa"])

        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            #st.write(dna_record)
            dna_seq = dna_record.seq

            details = st.radio(
                "Details of the DNA as provided by NCBI database:",
                ("DNA Record description", "Sequence"))
            if details == "DNA Record description":
                st.write(dna_record.description)
            elif details == "Sequence":
                st.write(dna_record.seq)

            #Nucleotide
            st.subheader("Nucleotide Frequency :")
            dna_freq = Counter(dna_seq)
            st.write(dna_freq)
            adenine_color = st.beta_color_picker("Toggle the Adenine Colour ")
            guanine_color = st.beta_color_picker("Toggle the Guanine Colour ")
            thymine_color = st.beta_color_picker("Toggle the Thymine Colour ")
            cytosine_color = st.beta_color_picker(
                "Toggle the Cytosine Colour ")

            if st.button("Plot frequency"):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[0].set_color(adenine_color)
                barlist[1].set_color(guanine_color)
                barlist[2].set_color(thymine_color)
                barlist[3].set_color(cytosine_color)
                st.pyplot()

            st.subheader("DNA complete Composition")

            gc_score = utils.gc_content(str(dna_seq))
            at_score = utils.at_content(str(dna_seq))
            st.json({
                "GC Content(for heat stability)": gc_score,
                "AT Content": at_score
            })

            #protein synthesis
            st.subheader("Protein Synthesis operations on the DNA :")
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))
            if st.checkbox("Transcription :"):
                st.write(dna_seq.transcribe())
            elif st.checkbox("Translation :"):
                st.write(dna_seq.translate())
            elif st.checkbox("Complement :"):
                st.write(dna_seq.complement())
            elif st.checkbox("Amino Acid frequency :"):
                st.write(aa_freq)

            elif st.checkbox("Plot the Amino Acid frequency :"):
                aa_color = st.beta_color_picker("Pick the Amino acid color:")
                #barlist= plt.bar(aa_freq.keys(),aa_freq.values(),color=aa_color)
                #barlist[2].set_color(aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values(), color=aa_color)
                st.pyplot()

            elif st.checkbox("The complete Amino acid name is given as"):
                aa_name = str(p1).replace("*", "")
                aa3 = utils.convert_1to3(aa_name)
                st.write(aa_name)
                st.write("========================")
                st.write(aa3)

                st.write("========================")
                st.write(utils.get_acid_name(aa3))

            #Top most amino acids

    elif choice == "Dotplot Analysis":
        st.subheader(
            "Generate Dotplot for the comparision between two DNA sequences here."
        )
        seq_file1 = st.file_uploader(
            "Upload the first .FASTA file for any DNA analysis of the considered Genome.",
            type=["fasta", "fa"])
        seq_file2 = st.file_uploader(
            "Upload the second .FASTA file for any DNA analysis of the considered Genome.",
            type=["fasta", "fa"])

        if seq_file1 and seq_file2 is not None:
            dna_record1 = SeqIO.read(seq_file1, "fasta")
            dna_record2 = SeqIO.read(seq_file2, "fasta")
            #st.write(dna_record)
            dna_seq1 = dna_record1.seq
            dna_seq2 = dna_record2.seq

            details = st.radio(
                "Details of the DNA as provided by NCBI database:",
                ("Record details from the NCBI database", "Gene Sequence"))
            if details == "Record details from the NCBI database":
                st.write(dna_record1.description)
                st.write("===And the other Record is decribed as :===")
                st.write(dna_record2.description)

            elif details == "Gene Sequence":
                st.write(dna_record1.seq)
                st.write("===And the other sequence can be given as: ===")
                st.write(dna_record2.seq)

            display_limit = st.number_input(
                "Select maximum number of Nucleotides", 10, 200, 50)
            if st.button("Push here for Dotplot :)"):
                st.write(
                    "Comparing the first {} nucleotide of the two sequences".
                    format(display_limit))
                dotplotx(dna_seq1[0:display_limit], dna_seq2[0:display_limit])
                st.pyplot()

    elif choice == "About us":
        st.subheader("About the application and about us :)")
Exemplo n.º 25
0
                         ("Length", "Frequency Table", "GC-Content",
                          "Melting-Temperature", "Plot Nucleotide Frequency"))
        if stats == "Length":
            st.write(length)
        elif stats == "Frequency Table":
            st.write("Frequency Table")
            st.write(pd.DataFrame.from_dict([dnafreq]))
        elif stats == "GC-Content":
            st.write(gccont)
        elif stats == "Melting-Temperature":
            st.write(melttemp)

        #PLOT = https://edinburgh-genome-foundry.github.io/DnaFeaturesViewer/examples/sequence_and_translation.html
        elif stats == "Plot Nucleotide Frequency":
            st.write("Pick color")
            adenine = st.beta_color_picker("ADENINE")
            thymine = st.beta_color_picker("THYMINE")
            guanine = st.beta_color_picker("GUANINE")
            cytosine = st.beta_color_picker("CYTOSINE")

            #SETTING BUTTON TO PICK COLOUR
            if st.button("Plot"):
                barplot = plt.bar(dnafreq.keys(), dnafreq.values())

                #COLOUR PICKER FOR EACH BASE
                barplot[3].set_color(adenine)
                barplot[2].set_color(thymine)
                barplot[1].set_color(guanine)
                barplot[0].set_color(cytosine)

                #PLOTTING
Exemplo n.º 26
0
def main():
    """A Bioinformatics App used to visuallize recombination site"""
    st.title(
        "RSarbiter: a machine learning supported expert in prediction and analysis of recombination spots in S. cerevisiae"
    )
    menu = ["Intro", "DNA Sequence", "Dot Plot", "About"]
    choice = st.sidebar.selectbox("Select Activity", menu)
    if choice == "Intro":
        st.subheader("Intro to BioInformatics")
    elif choice == "DNA Sequence":
        st.subheader("DNA Sequence Analysis")
        seq_file = st.file_uploader("Upload FASTA File",
                                    type=["fasta", "fa", "txt"])
        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            # dna_record = list(SeqIO.parse(seq_file,"fasta"))
            dna_seq = dna_record.seq
            st.write(dna_record)
            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record.description)
            else:
                st.write(dna_record.seq)
            # Nucleotide Frequency
            st.subheader("Nucleotide Frequency")
            dan_freq = Counter(dna_seq)
            st.write(dan_freq)
            adenine_color = st.beta_color_picker("Adenine Color")
            thymine_color = st.beta_color_picker("thymine Color")
            cytosine_color = st.beta_color_picker("cytosine Color")
            guanine_color = st.beta_color_picker("guanine Color")
            if st.button("Plot Freq"):
                barlist = plt.bar(dan_freq.keys(), dan_freq.values())
                barlist[0].set_color(adenine_color)
                barlist[1].set_color(thymine_color)
                barlist[2].set_color(guanine_color)
                barlist[3].set_color(cytosine_color)
                st.pyplot()
            st.subheader("DNA composition")
            gc_content = utils.gc_content(dna_seq)
            at_content = utils.at_content(dna_seq)
            st.write({
                "GC Content": gc_content,
                "AT Content": at_content
            })  # st.write = st.json

            # Nucleotide Count
            nt_count = st.text_input("Enter Nucleotide Here",
                                     "Type Nucleotide Alphabet")
            st.write("Number of {} Nucleotide is {}".format(
                (nt_count),
                str(dna_seq).count(nt_count)))

            # Protein Synthesis
            st.subheader("Protein Synthesis")
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))
            if st.checkbox("Transcription"):
                st.write(dna_seq.transcribe())
            # Top Most Common Amino
            elif st.checkbox("Translation"):
                st.write(dna_seq.translate())
            elif st.checkbox("Complement"):
                st.write(dna_seq.complement())
            elif st.checkbox("AA Frequency"):
                st.write(aa_freq)
            elif st.checkbox("Plot AA Frequency"):
                aa_color = st.beta_color_picker("Pick An Amino Acid Color")
                # barlist = plt.bar(aa_freq.keys(),aa_freq.values())
                # barlist[2].set_color(aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values(), color=aa_color)
                st.pyplot()
            elif st.checkbox("Full Amino Acid Name"):
                aa_name = str(p1).replace("*", "")
                aa3 = utils.convert_1to3(aa_name)
                st.write(aa_name)
                st.write("======================")
                st.write(aa3)
                st.write("======================")
                st.write(utils.get_acid_name(aa3))

    elif choice == "Dot Plot":
        st.subheader("Generate a Dot Plot For Two Sequences")
        # seq_file1 = st.file_uploader("Upload 1st FASTA File",type=["fasta","fa"])
        # seq_file2 = st.file_uploader("Upload 2nd FASTA File",type=["fasta","fa"])

        # if seq_file1 and seq_file2 is not None:
        #     dna_record1 = SeqIO.read(seq_file1,"fasta")
        #     dna_record2 = SeqIO.read(seq_file2,"fasta")
        #     # st.write(dna_record)
        #     dna_seq1 = dna_record1.seq
        #     dna_seq2 = dna_record2.seq

        #     details = st.radio("Details",("Description","Sequence"))
        #     if details == "Description":
        #         st.write(dna_record1.description)
        #         st.write("=====================")
        #         st.write(dna_record2.description)
        #     elif details == "Sequence":
        #         st.write(dna_record1.seq)
        #         st.write("=====================")
        #         st.write(dna_record2.seq)

        #     cus_limit = st.number_input("Select Max number of Nucleotide",10,200,50)
        #     if st.button("Dot Plot"):
        #         st.write("Comparing the first {} Nucleotide of the Two Sequences".format(cus_limit))
        #         dotplotx(dna_seq1[0:cus_limit],dna_seq2[0:cus_limit])

        #         st.pyplot()

        seq_file_1 = st.file_uploader("Upload 1st FASTA File",
                                      type=["fasta", "fa", "txt"])
        seq_file_2 = st.file_uploader("Upload 2nd FASTA File",
                                      type=["fasta", "fa", "txt"])

        if seq_file_1 and seq_file_2 is not None:
            dna_record_1 = SeqIO.read(seq_file_1, "fasta")
            dna_record_2 = SeqIO.read(seq_file_2, "fasta")
            dna_seq_1 = dna_record_1.seq
            dna_seq_2 = dna_record_2.seq

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record_1.description)
                st.write("======================")
                st.write(dna_record_2.description)
            elif details == "Sequence":
                st.write(dna_record_1.seq)
                st.write("==============")
                st.write(dna_record_2.seq)
            cus_limit = st.number_input("Select Max Number of Nucleotide", 10,
                                        200, 50)
            if st.button("Dot Plot"):
                st.write(
                    "Comparing The First {} Nucleotide of The Two Sequence".
                    format(cus_limit))
                dotplotx(dna_seq_1[0:cus_limit], dna_seq_2[0:cus_limit])
                st.pyplot()

    elif choice == "About":
        st.subheader("About")
Exemplo n.º 27
0
 def test_invalid_value_type_error(self):
     """Tests that when the value type is invalid, an exception is generated"""
     with pytest.raises(StreamlitAPIException) as exc_message:
         st.beta_color_picker("the label", 1234567)
# Upload a custom background image for the wallpaper
custom_bg_img = st.file_uploader(
    "You can upload a custom background image to replace the default black one with 640x1280 dimensions (otherwise it is resized)",
    type=["png", "jpg"])
# Save the uploaded image (deleted from the server at the end of the script)
if custom_bg_img != None:
    custom_bg_name = "custom_bg_img.png"
    custom_bg_path = os.path.join("static", "resources", custom_bg_name)
    pil_custom_bg_img = Image.open(custom_bg_img).resize(
        (640, 1280)).save(custom_bg_path)

# Change the operator theme color
# Using the beta version until the generally available version is fixed in Streamlit
#custom_op_color = st.color_picker("Feel free to change the operator theme color", op_default_color)
custom_op_color = st.beta_color_picker(
    "Feel free to change the operator theme color", op_default_color)

# Put together relevant operator information in a single dictionary
operator_info = {
    "E0 art": e0_art,
    "E2 art": e2_art,
    "skins": skins_available,
    "bg_chosen": background_art,
    "fg_chosen": foreground_art
}

# Get the url for fore and background art
fg_art_url = utils.get_art_url(foreground_art, operator_info)
bg_art_url = utils.get_art_url(background_art, operator_info)

# Create the image name string
Exemplo n.º 29
0
def main():
    show_menu()
    st.header("Select Community")

    # Select state
    states = os.listdir(STATES_FOLDER)
    state = st.selectbox("Select State", states)

    # select county
    counties = os.listdir(STATES_FOLDER + state)
    county = st.selectbox("Select County", counties)

    police_data, budget_df = create_budget_json(state, county)
    st.write(budget_df)

    # Show budget for year
    money = "$" + f'{police_data["budget"]:,}'
    header_string = (
        # "For "
        # + str(police_data["year"])
        # + " "
        str(county) + " County, " + str(state) + " has a police budget of " +
        str(money))
    wrapped_string = textwrap.wrap(header_string, width=30)
    # st.header(wrapped_string)

    fonts = ["fonts/Chunk_Five_Print.otf"]

    fonts.extend(glob.glob("fonts/*"))
    font = st.selectbox("Select Font", fonts)

    bg_color = st.beta_color_picker("Background color", "#496D89")
    st.write("The current  background color is", bg_color)

    text_color = st.beta_color_picker("Text color", "#FFFFFF")
    st.write("The current text color is", text_color)

    image = draw_image(wrapped_string, bg_color, text_color, font)

    st.image(image, use_column_width=True)

    st.write("source: " + str(police_data["source"]))
    defund = st.slider("Defund %", 0, 100, 20)

    defund_decmial = float(defund / 100)
    reinvest_money = float(police_data["budget"]) * defund_decmial
    reinvest_money_string = "$" + f"{int(reinvest_money):,}"

    investments = ["Education", "Healthcare", "Social Programs"]
    realocate = st.selectbox("Reinvest", investments)

    realoc_str = ("By defunding the police by " + str(defund) +
                  "% we can invest " + reinvest_money_string + " into " +
                  realocate)

    wrapped_string = textwrap.wrap(realoc_str, width=30)
    # st.header(realoc_str)
    image = draw_image(wrapped_string, bg_color, text_color, font)

    st.image(image, use_column_width=True)

    # based on input show what we can do...
    make_investment_image(realocate, reinvest_money, bg_color, text_color,
                          font)

    # TODO make this another "app" in sidebar for users to select
    # TODO have way to select different visualizations
    chart_types = [BAR_CHART, PIE_CHART]
    selected_chart = st.selectbox("Chart Types", chart_types)
    CHART_DICT.get(selected_chart)(budget_df)
    # bar_chart = viz.bar_graph(budget_df)
    # st.altair_chart(altair_chart(budget_df), use_container_width=True)

    wrapped_string = textwrap.wrap(header_string + "\n" + realoc_str, width=30)
    uploaded_file = st.file_uploader("Choose an Image File")
    if uploaded_file is not None:
        try:
            bar_chart = Image.open(uploaded_file)
            bar_chart_banner(bar_chart, state, county, bg_color, font,
                             wrapped_string, text_color)
        except Exception as error:
            st.error(error)

    hide_streamlit_style = """
            <title> Half Explot </title>
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            .sidebar .sidebar-content {background-image: linear-gradient(180deg,#4CA1AF,#2c3e50);}
            .btn-outline-secondary {
            border-color: #09ab3b85;
            color: #f9f9f9;
            }
            body {
            color: #fafafa;
            text-align: left;
            background-color: #262730;
            }
            </style>
            """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)
Exemplo n.º 30
0
def main():
    image = Image.open('b2.png')
    st.image(image, width=200)
    st.title("Trisakti Bioinformatics Application")
    st.title("Powered by Python")

    menu = ["Intro", "About", "DNA Sequence", "DotPlot"]
    choice = st.sidebar.selectbox("Select Activity", menu)

    if choice == "Intro":
        st.subheader("Intro to BioInformatics")
        image = Image.open('dna.png')
        st.image(image, width=800)

        st.subheader("Bioinformatics")
        "Bioinformatika merupakan cabang ilmu dari biologi yang mengkombinasikan penggunaan komputerisasi dengan karakterisik molekuler biologi. Kombinasi ini disebabkan karena perkembangan teknologi informasi yang sangat pesat, sehingga memudahkan untuk dilakukannya penelitian, serta dapat memberikan informasi yang akurat berdasarkan pengelolaan data. Bioinformatika mempelajari interpretasi biologis data, dan evolusi berbagai bentuk kehidupan dari pendekatan komputasi."

        st.subheader("DNA")
        "DNA adalah singkatan dari asam deoksiribonukleat, yang merupakan molekul yang menyimpan informasi genetik utama dalam sel. Nukleotida terdiri dari tiga bagian: gugus fosfat, gula pentosa (gula ribosa), dan basa. Basisnya terdiri dari empat jenis: adenin (A), guanin (G), sitosin (C), dan timin (T). A dan G adalah purin dengan dua cincin menyatu. C dan T adalah pirimidin dengan satu cincin tunggal. Selain DNA, ada jenis nukleotida lain yang disebut RNA atau asam ribonukleat."

        st.subheader("Protein/Amino Acid")
        "Asam amino adalah senyawa organik yang memiliki gugus fungsional karboksil (-COOH) dan amina (biasanya -NH2). Dalam biokimia sering kali pengertiannya dipersempit: keduanya terikat pada satu atom karbon (C) yang sama (disebut atom C alfa atau α). Gugus karboksil memberikan sifat asam dan gugus amina memberikan sifat basa. Dalam bentuk larutan, asam amino bersifat amfoterik: cenderung menjadi asam pada larutan basa dan menjadi basa pada larutan asam."

        st.subheader("Biopython")
        "Biopython adalah seperangkat alat yang tersedia secara gratis untuk komputasi biologis yang ditulis dengan Python oleh tim pengembang internasional. Aplikasi ini dibuat dan dikembangkan dengan bahasa pemrograman python yang mana menggunakan library biopython untuk proses eksplorasi dan ekstraksi data. Dalam eksplorasi dan ekstraksi data, biopython dapat melakukan proses comparing sequences DNA dan transtlation Nucleotide DNA ke Amino Acid penyusun protein. Berikut ini merupakan tabel Codon transtlation dari Nucleotide ke Amino Acid."
        image = Image.open('protein.png')
        st.image(image, width=800)

    elif choice == "About":

        st.subheader("Sejarah Awal Coronavirus")
        "Coronavirus pertama kali ditemukan pada pertengahan tahun 1960 dengan jenis HCoV-229E. Virus ini bermutasi selama 56 tahun sampai pada tahun 2020 tercatat ada tujuh dari banyaknya jenis spesies virus corona yang menginfeksi manusia muali dari Alpha Coronavirus, Beta Coronavirus, SARS, dan juga MERS. Evolusi dari jenis spesies virus corona dapat terlihat pada gambar di bawah ini."
        image = Image.open('mutasi.PNG')
        st.image(image, width=800)

        st.subheader("Corona Virus Disease 2019")
        "Pandemi koronavirus 2019 (bahasa Inggris: coronavirus disease 2019, disingkat COVID-19) adalah penyakit menular yang disebabkan oleh SARS-CoV-2, salah satu jenis koronavirus. Penyakit ini mengakibatkan pandemi koronavirus 2019–2020.Penderita COVID-19 dapat mengalami demam, batuk kering, dan kesulitan bernapas.Sakit tenggorokan, pilek, atau bersin-bersin lebih jarang ditemukan.Pada penderita yang paling rentan, penyakit ini dapat berujung pada pneumonia dan kegagalan multiorgan.Infeksi menyebar dari satu orang ke orang lain melalui percikan (droplet) dari saluran pernapasan yang sering dihasilkan saat batuk atau bersin. Waktu dari paparan virus hingga timbulnya gejala klinis berkisar antara 1–14 hari dengan rata-rata 5 hari. Metode standar diagnosis adalah uji reaksi berantai polimerase transkripsi-balik (rRT-PCR) dari usap nasofaring atau sampel dahak dengan hasil dalam beberapa jam hingga 2 hari. Pemeriksaan antibodi dari sampel serum darah juga dapat digunakan dengan hasil dalam beberapa hari. Infeksi juga dapat didiagnosis dari kombinasi gejala, faktor risiko, dan pemindaian tomografi terkomputasi pada dada yang menunjukkan gejala pneumonia."

        st.subheader("Tujuan Pembuatan Aplikasi")
        "Tujuan pembuatan dan pengembangan aplikasi ini adalah agar dapat membantu para peneliti dalam menganalisis informasi yang ada pada data DNA dengan bentuk visualisasi diagram plot. Juga hasil informasi dari ekstraksi data DNA menghasilkan pola/patern transtlation protein dari sample DNA Coronavirus. Aplikasi ini dapat memberi hasil persentase similaritas sequencing alignment DNA, sehingga terlihat adanya mutasi genetik yang terjadi."

        st.subheader(
            "Website ini dalam tahap pengembangan & digunakan untuk project penelitian."
        )
        st.subheader("contact : hafiz065001600009.trisakti.ac.id")

    elif choice == "DNA Sequence":
        st.subheader("DNA Sequence Analysis")

        seq_file = st.file_uploader("Upload FASTA File",
                                    type=["fasta", "fa", "txt"])

        if seq_file is not None:
            dna_record = SeqIO.read(seq_file, "fasta")
            #st.write(dna_record)
            dna_seq = dna_record.seq

            details = st.radio("Details", ("Description", "Sequence"))
            if details == "Description":
                st.write(dna_record.description)
            elif details == "Sequence":
                st.write(dna_record.seq)

            # Frekuensi Nucleotide
            st.subheader("Nucleotide Frequency")
            dna_freq = Counter(dna_seq)
            st.write(dna_freq)
            adenine_color = st.beta_color_picker("Adenine Color")
            thymine_color = st.beta_color_picker("Thymine Color")
            guanine_color = st.beta_color_picker("Guanine Color")
            cytosil_color = st.beta_color_picker("Cytosil Color")

            if st.button("Plot Frequency"):
                barlist = plt.bar(dna_freq.keys(), dna_freq.values())
                barlist[2].set_color(adenine_color)
                barlist[3].set_color(thymine_color)
                barlist[1].set_color(guanine_color)
                barlist[0].set_color(cytosil_color)

                st.pyplot()

            st.subheader("DNA Composition")
            gc_score = utils.gc_content(str(dna_seq))
            at_score = utils.at_content(str(dna_seq))
            st.json({"GC Content": gc_score, "AT Content": at_score})

            # Count Nucleotide
            nt_count = st.text_input("Enter Nucleotide",
                                     "Type Nucleotide Alphabet")
            st.write("Number of {} Nucleotide is ::{}".format(
                (nt_count),
                str(dna_seq).count(nt_count)))

            # Protein Synthesis
            st.subheader("Protein Synthesis")
            p1 = dna_seq.translate()
            aa_freq = Counter(str(p1))

            if st.checkbox("Transcription"):
                st.write(dna_seq.transcribe())

            elif st.checkbox("Translation"):
                st.write(dna_seq.translate())

            elif st.checkbox("Complement"):
                st.write(dna_seq.complement())

            elif st.checkbox("Amino Acid Frequency"):
                st.write(aa_freq)

            elif st.checkbox("Plot Amino Acid Frequency"):
                aa_color = st.beta_color_picker("Pick An Amino Acid Color")
                #barlist = plt.bar(aa_freq.keys(),aa_freq.values())
                #barlist[2].set_color(aa_color)
                plt.bar(aa_freq.keys(), aa_freq.values(), color=aa_color)
                st.pyplot()

            elif st.checkbox("Full Amino Acid Name"):
                aa_name = str(p1).replace("*", "")
                aa3 = utils.convert_1to3(aa_name)
                st.write(aa_name)
                st.write("=========================")
                st.write(aa3)

                st.write("=========================")
                st.write(utils.get_acid_name(aa3))

    elif choice == "DotPlot":
        st.subheader("Generate Dot Plot For Two Sequences")
        seq_file1 = st.file_uploader("Upload 1st FASTA File",
                                     type=["fasta", "fa"])
        seq_file2 = st.file_uploader("Upload 2nd FASTA File",
                                     type=["fasta", "fa"])

        if seq_file1 and seq_file2 is not None:
            dna_record1 = SeqIO.read(seq_file1, "fasta")
            dna_record2 = SeqIO.read(seq_file2, "fasta")
            # st.write(dna_record)
            dna_seq1 = dna_record1.seq
            dna_seq2 = dna_record2.seq
            dna_freq1 = Counter(dna_seq1)
            dna_freq2 = Counter(dna_seq2)
            p1 = dna_seq1.translate()
            aa_freq1 = Counter(str(p1))
            p2 = dna_seq2.translate()
            aa_freq2 = Counter(str(p2))
            details = st.radio(
                "Details",
                ("Description", "Sequence", "Nucleotide Frequency",
                 "Nucleotide Plot Frequency", "Amino Acid Frequency",
                 "Amino Acid Plot Frequency"))
            if details == "Description":
                st.write(dna_record1.description)
                st.write("=====================")
                st.write(dna_record2.description)
                st.subheader("DNA Composition")
                gc_score1 = utils.gc_content(str(dna_seq1))
                at_score1 = utils.at_content(str(dna_seq1))
                st.json({"GC Content": gc_score1, "AT Content": at_score1})
                gc_score2 = utils.gc_content(str(dna_seq2))
                at_score2 = utils.at_content(str(dna_seq2))
                st.json({"GC Content": gc_score2, "AT Content": at_score2})
            elif details == "Sequence":
                st.write(dna_record1.seq)
                st.write(
                    "========================================================================="
                )
                st.write(dna_record2.seq)
            elif details == "Nucleotide Frequency":
                st.write(dna_freq1)
                st.write("=====================")
                st.write(dna_freq2)
            elif details == "Nucleotide Plot Frequency":
                barlist = plt.bar(dna_freq1.keys(), dna_freq1.values())
                st.pyplot()
                st.write(
                    "=========================================================================="
                )
                barlist = plt.bar(dna_freq2.keys(), dna_freq2.values())
                st.pyplot()
            elif details == "Amino Acid Frequency":
                st.write(aa_freq1)
                st.write("=====================")
                st.write(aa_freq2)
            elif details == "Amino Acid Plot Frequency":
                plt.bar(aa_freq1.keys(), aa_freq1.values())
                st.pyplot()
                st.write(
                    "=========================================================================="
                )
                plt.bar(aa_freq2.keys(), aa_freq2.values())
                st.pyplot()
            cus_limit = st.number_input(
                "Select Max number of Nucleotide (Minimum 100)", 100, 40000,
                10000)
            if st.button("Dot Plot"):
                st.write(
                    "Comparing the first {} Nucleotide of the Two Sequences".
                    format(cus_limit))
                dotplotx(dna_seq1[0:cus_limit], dna_seq2[0:cus_limit])

                st.pyplot()
            elif st.button("Similarity"):
                st.write(
                    "Similarity of Comparing the first {} Nucleotide of the Two Sequences"
                    .format(cus_limit))
                r = pairwise2.align.globalxx(dna_seq1[0:cus_limit],
                                             dna_seq2[0:cus_limit],
                                             one_alignment_only=True,
                                             score_only=True)
                r / len(dna_seq1[0:cus_limit]) * 100