This function calculates the bray-curtis distance between each pair of vectors in a dataframe.
Args:
df: the dataframe containing the vectors
feature_axis: the axis of the dataframe that contains the vectors
threads: the number of threads used to calculate the distances
Returns:
a dataframe containing the distances between each pair of vectors
defcalculate_dist(df:pl.DataFrame,feature_axis:int=1,threads:int=8)->pl.DataFrame:""" This function calculates the bray-curtis distance between each pair of vectors in a dataframe. Args: df: the dataframe containing the vectors feature_axis: the axis of the dataframe that contains the vectors threads: the number of threads used to calculate the distances Returns: a dataframe containing the distances between each pair of vectors """iffeature_axis==0:df=df.transpose(include_header=True,header_name="name")sem=Semaphore(threads)names,rows=_numeric_rows(df)res=[[0.0for_innames]for_innames]pairs=[]tasks=[]foriinrange(len(rows)):forjinrange(i+1,len(rows)):pairs.append((i,j))tasks.append(Pair(rows[i],rows[j],sem))fortaskintasks:task.start()foridx,taskinenumerate(tasks):task.join()i1,j1=pairs[idx]res[i1][j1]=task.resres[j1][i1]=task.resreturnpl.DataFrame([{"name":name,**{names[j]:row[j]forjinrange(len(names))}}forname,rowinzip(names,res)])
This function scales the vectors in a dataframe to have unit norm.
Args:
df (pd.DataFrame): the dataframe containing the vectors
feature_axis (int): the axis of the dataframe that contains the vectors
inplace (bool): whether to scale the vectors in place
Returns:
(pd.DataFrame|None): the scaled dataframe; if inplace is True, returns None
defscaler(df:pl.DataFrame,feature_axis:int=1,inplace:bool=False)->pl.DataFrame|None:""" This function scales the vectors in a dataframe to have unit norm. Args: df (pd.DataFrame): the dataframe containing the vectors feature_axis (int): the axis of the dataframe that contains the vectors inplace (bool): whether to scale the vectors in place Returns: (pd.DataFrame|None): the scaled dataframe; if inplace is True, returns None """iffeature_axis==0:df=df.transpose(include_header=True,header_name="name")columns=df.columnsscaled_rows=[]forrowindf.select(pl.all().cast(pl.Float64,strict=False).fill_null(0.0)).to_dicts():total=sum(row.values())scaled_rows.append({key:(value/totaliftotalelse0.0)forkey,valueinrow.items()})ifinplace:returnNonereturnpl.DataFrame(scaled_rows,schema={column:pl.Float64forcolumnincolumns})
This class is used to calculate the distance between two vectors. it is a subclass of Thread.
This design is used to do multi-threading given that multiple pairs of vectors can be calculated simultaneously.
Given two vectors, this function calculates the bray-curtis distance between them.
Args:
u: the first vector
v: the second vector
semaphore: the semaphore used to control the number of running threads (This is automatically handled by the calculate_dist function)
def__init__(self,u:Iterable,v:Iterable,semaphore:Semaphore):""" Given two vectors, this function calculates the bray-curtis distance between them. Args: u: the first vector v: the second vector semaphore: the semaphore used to control the number of running threads (This is automatically handled by the calculate_dist function) """super().__init__()self.u=uself.v=vself.semaphore=semaphore