diff --git a/HW4_Uzun/AAmigo.py b/HW4_Uzun/AAmigo.py new file mode 100644 index 0000000..96e2722 --- /dev/null +++ b/HW4_Uzun/AAmigo.py @@ -0,0 +1,181 @@ +def protein_mass(seq: str): + """ + + Calculate the mass (Da) of a protein based on its amino acids sequence. + Takes a string of amino acids, returns the molecular weight in Da. + Amino acids in the string should be indicated as one-letter symbols. + + """ + aa_seq = list(seq.upper()) + mass_dictionary = dict({'A': 89, 'R': 174, 'N': 132, 'D': 133, 'C': 121, 'Q': 146, 'E': 147, 'Z': 147, + 'G': 75, 'H': 155, 'I': 131, 'L': 131, 'K': 146, 'M': 149, 'F': 165, 'P': 115, 'S': 105, + 'T': 119, 'W': 204, 'Y': 181, 'V': 117}) + mass = 0 + for amino_acid in aa_seq: + mass += mass_dictionary[amino_acid] + + return mass + + +def amino_acid_profile(seq: str): + """ + + Displays the proportion of hydrophobic, polar, negatively and positively charged amino acids in the protein. + Takes a string of amino acids, returns a dictionary. + Amino acids in the string should be indicated as one-letter symbols. + + """ + aa_seq = list(seq.upper()) + aa_biochemistry = dict( + {'hydrophobic': ['G', 'A', 'V', 'L', 'I', 'P', 'F', 'M', 'W'], 'polar': ['S', 'T', 'C', 'N', 'Q', 'Y'], + '- charged': ['E', 'D'], '+ charged': ['K', 'H', 'R']}) + profile = dict({'hydrophobic': 0.0, 'polar': 0.0, '- charged': 0.0, '+ charged': 0.0}) + + for amino_acid in aa_seq: + for group_name, group_list in aa_biochemistry.items(): + if amino_acid in group_list: + profile[group_name] += 1 + + for group, count in profile.items(): + profile[group] = round((count/len(seq)), 2) + return profile + + +def amino_acid_substring(seq: str): + """ + + Searches for a substring of amino acids in the entire amino acid sequence. + Takes a string of amino acids and a substring, which should be found. + Returns the position where the searched one was found for the first time. + Amino acids in the string should be indicated as one-letter symbols. + + """ + aa_seq = list(seq) + aa_seq_upper = [] + for sequences in aa_seq: + upper_case = sequences.upper() + aa_seq_upper.append(upper_case) + amino_acids = aa_seq_upper[:-1] + substring = aa_seq_upper[-1] + results = [] + for sequences in amino_acids: + subst = sequences.find(substring) + results.append(subst) + return results + + +def amino_acid_count(seq: str): + """ + + Finds how many times a particular sequence(s) occurs in the original one. + Takes a string of amino acids and a substring, which should be counted. + Returns the count of searched amino acids. + Amino acids in the string should be indicated as one-letter symbols. + + """ + aa_seq = list(seq) + aa_seq_upper = [] + for sequences in aa_seq: + upper_case = sequences.upper() + aa_seq_upper.append(upper_case) + amino_acids = aa_seq_upper[:-1] + substring = aa_seq_upper[-1] + results = [] + for sequences in amino_acids: + aa_count = sequences.count(substring) + results.append(aa_count) + return results + + +def protein_length(*seq: str): + """ + + Calculate the length (number of amino acids) of a protein. + Takes a string of amino acids, returns the number. + Amino acids in the string should be indicated as one-letter symbols. + + """ + lengths = [] + + for sequences in seq: + lengths.append(len(sequences)) + + return lengths + + +def essential_amino_acids(*seq: str): + """ + + Calculate the number of essential amino acids based on its amino acids sequence. + Takes a string of amino acids, returns only the essential amino acids. + Amino acids in the string should be indicated as one-letter symbols. + + """ + eaa_dictionary = ['H', 'I', 'K', 'L', 'M', 'F', 'T', 'W', 'V', 'h', 'i', 'k', 'l', 'm', 'f', 't', 'w', 'v'] + eaa_list = [] + + for sequences in seq: + eaa_seq = [] + for amino_acid in sequences: + if amino_acid in eaa_dictionary: + eaa_seq.append(amino_acid) + eaa_list.append(eaa_seq) + + return eaa_list + + +def aa_tools(*args): + """ + + Main function for amino acid sequences processing. + Parameters: *args (str) - amino acid sequences and operation. + Returns: List of results or None if non-amino acid chars found. + + """ + seq = args[:-1] + operation = args[-1] + non_aa_chars = set('BJOUXbjoux') + contains_non_aa = False + + for sequence in seq: + contains_non_aa = False + for amino_acid in sequence: + if amino_acid in non_aa_chars: + contains_non_aa = True + break + if contains_non_aa: + break + if contains_non_aa: + return None + + results = [] + + for sequence in seq: + if operation == "protein_mass": + result = protein_mass(sequence) + results.append(result) + + elif operation == "amino_acid_profile": + result = amino_acid_profile(sequence) + results.append(result) + + if operation == "amino_acid_substring": + result = amino_acid_substring(seq) + return result + + if operation == "amino_acid_count": + result = amino_acid_count(seq) + return result + + if operation == "protein_length": + result = protein_length(sequence) + results.append(result) + + if operation == "essential_amino_acids": + result = essential_amino_acids(sequence) + results.append(result) + + return results + + +aa_tools() diff --git a/HW4_Uzun/README.md b/HW4_Uzun/README.md new file mode 100644 index 0000000..9f00ab7 --- /dev/null +++ b/HW4_Uzun/README.md @@ -0,0 +1,92 @@ +# AAmigo +This readme describes the user-friendly program AAmigo for performing various operations with amino acid sequences. + +AAmigo can perform different operations: +* Calculate the mass of a protein. +* Calculate the ratio of amino acids with different polarities in a protein +* Find for a particular amino acid(s) in the entire sequence +* Calculate amino acid's occurrence in a sequence +* Calculate amino acid sequence(s) length +* Finds essential amino acids (in humans) in a sequence(s) + +## Usage +1. Clone this repo using SSH or HTTPS: +```bash +git clone git@github.com:uzunmasha/HW4_Functions2.git +``` +**or** +```bash +git clone https://github.com/uzunmasha/HW4_Functions2.git +``` +2. Launch the program with the required function (listed below) in a code interpreter like Jupyter Notebook. +3. Enjoy your results! + +## List of functions: +For all functions, amino acids in the sequences should be indicated as one-letter symbols. Letters can be uppercase or lowercase. + +### protein_mass +This function calculates the mass (Da) of a protein based on its amino acid sequence. As input, it takes a string of amino acids and returns the molecular weight in Da. +Usage example: +```python +aa_tools('MARY', 'protein_mass') #593 (in Da) +``` +### amino_acid_profile +This function displays the proportion of hydrophobic, polar, negatively, and positively charged amino acids in the protein. It takes a string of amino acids, and returns a dictionary with the result. +Usage example: +```python +aa_tools('EEKFG', 'amino_acid_profile') #{'hydrophobic': 0.4, 'polar': 0.0, '- charged': 0.4, '+ charged': 0.2} +``` +### amino_acid_substring +This function searches for the presence of particular amino acid(s) in the entire amino acid sequence. As input, it takes a string of amino acids and a substring that needs to be found. All sequences and subsequence should be comma-separated. Any number of amino acid sequences is possible. The searched substring should be one and it should be pointed last. As an output, the function returns the position in the original sequence where the searched element was found for the first time. +Usage example: +```python +aa_tools('RNwDeACEQEZ', 'E','amino_acid_substring') #4 +aa_tools('RNwDeACEQEZ', 'DFKAaaE','A','amino_acid_substring') #[5, 3] +``` +### amino_acid_count +This function finds how many times a particular amino acid or sequence of several amino acids occurs in the original sequence. As input, it takes a string of amino acids and a substring that needs to be counted. All sequences and subsequence should be comma-separated. Any number of amino acid sequences is possible. The searched substring should be one and it should be pointed last. As an output, the function returns the count of searched amino acid(s). +Usage example: +```python +aa_tools('GHcLfKF','f','amino_acid_count') #2 +aa_tools('HILAKMaF', 'GDaKFAAE','A','amino_acid_count') #[2, 3] +``` +### protein_length +This function can analyze an aminoacid sequence and gives a length of it (number of amino acids). Any number of amino acid sequences is possible. All sequences should be comma-separated. As input, it takes a string or strings of amino acids, as an output, the function returns the length of each protein. +Usage example: +```python +aa_tools('KKNNfF', 'KKFFRRVV', 'KK', 'protein_length') #[6, 8, 2] +``` +### essential_amino_acids +This function can analyze an amino acid sequence and gives a list of essential amino acids (in humans) that are present in the sequence. +Any number of amino acid sequences is possible. All sequences should be comma-separated. As input, it takes a string or strings of amino acids, as an output, the function returns essential amino acids for each sequence. +Usage example: +```python +aa_tools('KKNNfF', 'KKFFRRVV', 'KK', 'essential_amino_acids') #[['K', 'K', 'f', 'F'], ['K', 'K', 'F', 'F', 'V', 'V'], ['K', 'K']] +``` + +## Troubleshooting +* In function `'amino_acid_substring'` the position counting starts at 0, so don't be confused if the second element in the sequence has the output [1]. +* In functions `'amino_acid_substring'` and `'amino_acid_count'` output [-1] means that there is no such element in the sequence. +* In functions `'amino_acid_substring'` and `'amino_acid_count'` the error message "name '..' is not defined" means that the given argument is not quoted in the input string. + +## Bibliography +[1] Wu G. Amino acids: metabolism, functions, and nutrition. Amino Acids. 2009 May;37(1):1-17. doi: 10.1007/s00726-009-0269-0. + +## Developers and contacts +* Maria Uzun - contributed to `'amino_acid_substring'`, `'amino_acid_count'`, and `'aa_tools'` functions. +* Maria Babaeva - contributed to `'protein_mass'` and `'amino_acid_profile'` functions. +* Kristina Zhur - contributed to `'protein_length'` and `'essential_amino_acids'` functions. +* Julia the Cat - team's emotional support. + + +![photo_2023-09-26_18-33-49_3](https://github.com/uzunmasha/HW4_Functions2/assets/44806106/63fdea24-5c0a-4650-8bed-181871aa540f) + + +In case of non-working code: + +* Please blame the one who has the paws +* Report any problems directly to the GitHub issue tracker + +or + +* Send your feedback to uzunmasha@gmail.com diff --git a/README.md b/README.md deleted file mode 100644 index f918170..0000000 --- a/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# HW 4. Functions 2 -> *This is the repo for the fourth homework of the BI Python 2023 course* - -### Homework description - -На прошлой неделе вы делали утилиту для работы с последовательностями нуклеиновых кислот (с весьма строгим ТЗ). Пришло время для чего-то более самостоятельного. - -#### Основное задание - - -Напишите утилиту для работы с последовательностями белков. Там должно быть минимум 5 различных операций, должна быть какая-то точка входа через которую пользователь будет всё это дело использовать. На этом, по сути, всё. Всё целиком зависит от вашей фантазии и креативности. Можете опираться на ДЗ №2 и №3. - -Самая главная часть задания - это файл `README.md`. Сделайте краткое введение, напишите описание тула, приведите документацию по использованию со списком аргументов. Добавьте примеры использования. Возможно, вы захотите сделать секцию Troubleshooting. ***Почему это нужно?*** В этот раз проверяющий не будет знать того, как должен работать ваш тул. Это ваш авторский код. Даже самая прекрасная функциональность, не будучи отраженной в README, скорее всего останется незамеченной. README - это ваш способ познакомить пользователя с тулом, показать всё лучше и обосновать, почему именно ваша команда должна получить наивысший балл. - -Есть люди которые, любят писать документации, а есть те - кто не любит. Найдите в вашей команде того, кто любит. И в будущем в своих рабочих проектах всегда держите рядом такого человек (или будьте им). - -Примеры некоторых README, которыми можно вдохновляться: - -- [MetaFX](https://github.com/ctlab/metafx), тул Артёма Иванова. Там еще и [wiki](https://github.com/ctlab/metafx/wiki) крутое. -- [samovar](https://github.com/nvaulin/samovar) -- [MetaGEM](https://github.com/franciscozorrilla/metaGEM) -- [Pharokka](https://github.com/gbouras13/pharokka) - -Типовые секции, на которые стоит обратить внимание: Title, Overview, Usage, Options, Examples, Troubleshooting, Contacts. - -**Tехническое требование к заданию.** - -Это задание будет выполняться в командах по 3 человека. Каждый из членов команды должен внести ***как минимум*** 2 функции. Каждое внесение функции должно сопровождаться коммитом с осмысленным описанием коммита. Ниже приведена последовательность действий для успешного выполнения задания (аналогично ДЗ №2): - -1. Посмотрите состав своей команды здесь ([**ССЫЛКА**](https://docs.google.com/spreadsheets/d/1KMBBBu8LqauRpDJb0v1ldPwpvzNn8-KakcHexAcqLsE/edit?usp=sharing)). -2. Тимлид делает форк данного репозитория. **В форке создает ветку `HW4_`, в ветке создает папку `HW4_`, в этой папке вы всё делаете.** -3. Члены команды могут либо делать свои форки, либо работать в репозитории тимлида в качестве колабораторов ("contributors"). В любом случае делаете клоны => пишите код локально => пушите. -4. В конце тимлид делайет pull-request из `HW4_` своего репозитория в `main` этого. - - -А также: -- Сопроводите программу лучшим `README.md` файлом в вашей жизни (на английском языке). -- В этом ДЗ проблемы с качеством кода (нейминги, пустые строки, анноатции типов, док.стринги, пробелы) могут привести к снижению балла. Воспользуйтесь линтерами чтобы себя обезопасить. IDE по типу PyCharm или VSCode имеют фунцонал по авто-исправлению многих проблем такого рода. - -Автотестов на GitHub в этом ДЗ нет, но вы можете прогнать линтеры на качество кода локально (как в ДЗ №3, подробнее читайте [тут](https://plausible-cannon-091.notion.site/Code-auto-checks-02b2ea69c1d545fca07b50ce5933ed5f?pvs=4)). - -- Программа должна сохранять регистр символов. -- Программа должна работать только с последовательностями белков. -- Запрещается использование сторонних модулей. - - -### Форма сдачи - -Прикрепите ссылку на pull-request тимлида в Google Class (можете сделать от лица каждого члена команды, но это не обязательно). - - -### Pазбалловка - -- За каждую из 5 операций - максимум **1.5 балла** -- За README - максимум **2.5 балла** -- Если вы не внесли как минимум 2 функции от себя, вы получаете 0 баллов (на баллы остальных членов команды это не влияет). -- За фото созвона в README можно получить 0.2 доп. балла (но не более 10 баллов суммарно) - - - -### **Предполагаемый учебный результат** - -Это задание позволит вам проявить креативность и учиться быть не только кодером, но и автором. Также это задание поможет окончательно закрепить материал по функциям который мы прошли. - -Удачи! ✨✨