Skip to content

Instantly share code, notes, and snippets.

View StephenFordham's full-sized avatar

Stephen Fordham StephenFordham

View GitHub Profile
@StephenFordham
StephenFordham / baseline_correction_normalisation.py
Created September 9, 2024 12:39
MALDI TOF MS baseline correction and normalisation functions for antibiotic resistance prediction
# Function for baseline correction using a simple rolling minimum
import numpy as np
from scipy.signal import savgol_filter
def baseline_correction(intensities, window_size=50, poly_order=3):
baseline = savgol_filter(intensities, window_length=window_size, polyorder=poly_order)
corrected_intensities = intensities - baseline
corrected_intensities[corrected_intensities < 0] = 0 # Ensuring no negative intensities
return corrected_intensities
@StephenFordham
StephenFordham / Repeat_confirmation.py
Created August 8, 2024 17:58
Repeat_confirmation
from Bio import SeqIO
def read_fasta_sequence(file_path):
sequence = ""
with open(file_path, 'r') as file:
for line in file:
if not line.startswith('>'):
sequence += line.strip()
return sequence
@StephenFordham
StephenFordham / depth_calc.py
Created July 7, 2024 13:34
short_read_depth_calculation
def depth_calc(file, read_depth=0):
df = pd.read_csv(file, sep='\t', header=None)
df.columns = ['consensus', 'base_position', 'depth']
plasmid_length = df['base_position'].max()
base_coverage = df[df['depth'] > read_depth].__len__()
cov_perc = (base_coverage/plasmid_length) * 100
return cov_perc
@StephenFordham
StephenFordham / PRC_skillful_model.py
Created October 23, 2023 09:51
Precision-recall curve for a skillful model
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_curve, auc
import seaborn as sns
X, y = make_classification(n_samples=1000, n_classes=2, random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)
model = LogisticRegression(solver='lbfgs')
@StephenFordham
StephenFordham / AUC_ROC_model.py
Last active October 23, 2023 08:26
AUC ROC Skillful model comparison
import matplotlib.pyplot as plt
# ROC and AUC modules
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, roc_auc_score
import seaborn as sns
# generate 2 class dataset
X, y = make_classification(n_samples=1000, n_classes=2, weights=[0.5], random_state=1)
@StephenFordham
StephenFordham / init_constructor_decorator.py
Created June 9, 2022 18:08
init_constructor_decorator
# __init__ method with a decorator
def attr_validation(method):
def inner(ref, name, age, location):
for attr in [name, location]:
if not isinstance(attr, str):
raise TypeError('Name and Location attributes must be of type str')
if not isinstance(age, int):
raise TypeError('Age attributes must be of type int')
return method(ref, name, age, location)
return inner
@StephenFordham
StephenFordham / __setattr__part2.py
Created June 9, 2022 17:09
__setattr__catching_exceptions
e1 = Employees(46347832, 30, 'Bournemouth')
for key, value in e1.__dict__.items():
print('{}: {}'.format(key, value))
#Console output
TypeError: Only valid attributes of type string are accepted
@StephenFordham
StephenFordham / __setattr__magic_method.py
Created June 9, 2022 17:04
__setattr__magic_method
class Employees(object):
def __init__(self, name, age, location):
self._name = name
self._age = age
self._location = location
def __setattr__(self, key, value):
if key in ['_name', '_location']:
if not isinstance(value, str):
raise TypeError('Only valid attributes of type string are accepted')
class Employees(object):
def __init__(self, name, age, location):
self._name = name
self._age = age
self._location = location
def __call__(self, *args, **my_attr_dict):
if len(my_attr_dict) > 0:
try:
self._name = my_attr_dict['_name']
@StephenFordham
StephenFordham / Instantiating_Employees_objects.py
Created June 9, 2022 15:23
Instantiating an instance of the Employees class
class Employees(object):
def __init__(self, name, age, location):
self._name = name
self._age = age
self._location = location
e1 = Employees('stephen', 30, 'Bournemouth')
for key, value in e1.__dict__.items():
print('{}: {}'.format(key, value))