




from typing import Dict, Optional, Tuple

import torch


def 							__SCREAMING_SNAKE_CASE  (      snake_case_						):

						'''simple docstring'''


						_UpperCAmelCase													=					boundaries[1] - boundaries[0]
						_UpperCAmelCase													=					boundaries + step / 2
						_UpperCAmelCase													=					torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1						)]     ,   dim=0						)
						return bin_centers


def 							__SCREAMING_SNAKE_CASE  (      snake_case_     ,   snake_case_     ,   ):

						'''simple docstring'''


						_UpperCAmelCase													=					_calculate_bin_centers(__lowercase						)
						return (
						    torch.sum(aligned_distance_error_probs * bin_centers     ,   dim=-1						),
						    bin_centers[-1],
						)


def 							__SCREAMING_SNAKE_CASE  (      snake_case_     ,   snake_case_ = 31     ,   snake_case_ = 64     ,   **snake_case_     ,   ):

						'''simple docstring'''


						_UpperCAmelCase													=					torch.linspace(0     ,   __lowercase     ,   steps=(no_bins - 1)     ,   device=logits.device						)

						_UpperCAmelCase													=					torch.nn.functional.softmax(__lowercase     ,   dim=-1						)
						_UpperCAmelCase							,			_UpperCAmelCase													=					_calculate_expected_aligned_error(
						    alignment_confidence_breaks=__lowercase     ,   aligned_distance_error_probs=__lowercase     ,   )

						return {
						    "aligned_confidence_probs": aligned_confidence_probs,
						    "predicted_aligned_error": predicted_aligned_error,
						    "max_predicted_aligned_error": max_predicted_aligned_error,
						}





def 							__SCREAMING_SNAKE_CASE  (      snake_case_     ,   snake_case_ = None     ,   snake_case_ = 31     ,   snake_case_ = 64     ,   snake_case_ = 1e-8     ,   **snake_case_     ,   ):

						'''simple docstring'''


						if residue_weights is None:
												_UpperCAmelCase													=					logits.new_ones(logits.shape[-2]						)

						_UpperCAmelCase													=					torch.linspace(0     ,   __lowercase     ,   steps=(no_bins - 1)     ,   device=logits.device						)

						_UpperCAmelCase													=					_calculate_bin_centers(__lowercase						)
						torch.sum(__lowercase						)
						_UpperCAmelCase													=					logits.shape[-2]
						_UpperCAmelCase													=					max(__lowercase     ,   19						)

						_UpperCAmelCase													=					1.24 * (clipped_n - 15) ** (1.0 / 3) - 1.8

						_UpperCAmelCase													=					torch.nn.functional.softmax(__lowercase     ,   dim=-1						)

						_UpperCAmelCase													=					1.0 / (1 + (bin_centers**2) / (da**2))
						_UpperCAmelCase													=					torch.sum(probs * tm_per_bin     ,   dim=-1						)

						_UpperCAmelCase													=					residue_weights / (eps + residue_weights.sum())
						_UpperCAmelCase													=					torch.sum(predicted_tm_term * normed_residue_mask     ,   dim=-1						)

						_UpperCAmelCase													=					per_alignment * residue_weights

						_UpperCAmelCase													=					(weighted == torch.max(__lowercase						)).nonzero()[0]
						return per_alignment[tuple(__lowercase						)]










import itertools
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa

import datasets
from datasets.table import table_cast


lowercase_     :    Union[str, Any]      =			datasets.utils.logging.get_logger(__name__)






@dataclass
class    __lowerCAmelCase			(	datasets.BuilderConfig			):
			snake_case_				:			Optional[datasets.Features]								=					None






class    __lowerCAmelCase			(	datasets.ArrowBasedBuilder			):
			snake_case_				:			str								=					ArrowConfig







			def UpperCamelCase      (	self   :      Optional[int]				):




									"""simple docstring"""


									return datasets.DatasetInfo(features=self.config.features				)







			def UpperCamelCase      (	self   :      str   ,   snake_case__   :      Optional[int]				):




									"""simple docstring"""


									if not self.config.data_files:
															raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""				)
									_UpperCAmelCase													=					dl_manager.download_and_extract(self.config.data_files				)
									if isinstance(snake_case__   ,   (str, list, tuple)				):
															_UpperCAmelCase													=					data_files
															if isinstance(snake_case__   ,   snake_case__				):
																					_UpperCAmelCase													=					[files]
															# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
															_UpperCAmelCase													=					[dl_manager.iter_files(snake_case__				) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN   ,   gen_kwargs={"files": files}				)]
									_UpperCAmelCase													=					[]
									for split_name, files in data_files.items():
															if isinstance(snake_case__   ,   snake_case__				):
																					_UpperCAmelCase													=					[files]
															# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
															_UpperCAmelCase													=					[dl_manager.iter_files(snake_case__				) for file in files]
															# Infer features is they are stoed in the arrow schema
															if self.info.features is None:
																					for file in itertools.chain.from_iterable(snake_case__				):
																											with open(snake_case__   ,   "rb"				) as f:
																																	_UpperCAmelCase													=					datasets.Features.from_arrow_schema(pa.ipc.open_stream(snake_case__				).schema				)
																											break
															splits.append(datasets.SplitGenerator(name=snake_case__   ,   gen_kwargs={"files": files}				)				)
									return splits







			def UpperCamelCase      (	self   :      int   ,   snake_case__   :      pa.Table				):




									"""simple docstring"""


									if self.info.features is not None:
															# more expensive cast to support nested features with keys in a different order
															# allows str <-> int/float or str to Audio for example
															_UpperCAmelCase													=					table_cast(snake_case__   ,   self.info.features.arrow_schema				)
									return pa_table







			def UpperCamelCase      (	self   :      Optional[Any]   ,   snake_case__   :      int				):




									"""simple docstring"""


									for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case__				)				):
															with open(snake_case__   ,   "rb"				) as f:
																					try:
																											for batch_idx, record_batch in enumerate(pa.ipc.open_stream(snake_case__				)				):
																																	_UpperCAmelCase													=					pa.Table.from_batches([record_batch]				)
																																	# Uncomment for debugging (will print the Arrow table size and elements)
																																	# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																																	# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																	yield F"""{file_idx}_{batch_idx}""", self._cast_table(snake_case__				)
																					except ValueError as e:
																											logger.error(F"""Failed to read file '{file}' with error {type(snake_case__				)}: {e}"""				)
																											raise




