File size: 12,990 Bytes
6c482f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""
Domain Dataset Module for Cross-Domain Uncertainty Quantification

This module provides functionality for loading and managing datasets from different domains
for evaluating uncertainty quantification methods across domains.
"""

import os
import json
import pandas as pd
import numpy as np
from typing import List, Dict, Any, Union, Optional, Tuple
from datasets import load_dataset

class DomainDataset:
    """Base class for domain-specific datasets."""
    
    def __init__(self, name: str, domain: str):
        """
        Initialize the domain dataset.
        
        Args:
            name: Name of the dataset
            domain: Domain category (e.g., 'medical', 'legal', 'general')
        """
        self.name = name
        self.domain = domain
        self.data = None
    
    def load(self) -> None:
        """Load the dataset."""
        raise NotImplementedError("Subclasses must implement this method")
    
    def get_samples(self, n: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Get samples from the dataset.
        
        Args:
            n: Number of samples to return (None for all)
            
        Returns:
            List of samples with prompts and expected outputs
        """
        raise NotImplementedError("Subclasses must implement this method")
    
    def get_prompt_template(self) -> str:
        """
        Get the prompt template for this domain.
        
        Returns:
            Prompt template string
        """
        raise NotImplementedError("Subclasses must implement this method")


class MedicalQADataset(DomainDataset):
    """Dataset for medical question answering."""
    
    def __init__(self, data_path: Optional[str] = None):
        """
        Initialize the medical QA dataset.
        
        Args:
            data_path: Path to the dataset file (None to use default)
        """
        super().__init__("medical_qa", "medical")
        self.data_path = data_path
    
    def load(self) -> None:
        """Load the medical QA dataset."""
        if self.data_path and os.path.exists(self.data_path):
            # Load from local file if available
            if self.data_path.endswith('.csv'):
                self.data = pd.read_csv(self.data_path)
            elif self.data_path.endswith('.json'):
                with open(self.data_path, 'r') as f:
                    self.data = json.load(f)
            else:
                raise ValueError(f"Unsupported file format: {self.data_path}")
        else:
            # Use a sample of the MedMCQA dataset from Hugging Face
            try:
                dataset = load_dataset("medmcqa", split="train[:100]")
                self.data = dataset.to_pandas()
            except Exception as e:
                # Fallback to synthetic data if dataset loading fails
                print(f"Failed to load MedMCQA dataset: {e}")
                self.data = self._create_synthetic_data()
    
    def _create_synthetic_data(self) -> pd.DataFrame:
        """Create synthetic medical QA data for testing."""
        questions = [
            "What are the common symptoms of myocardial infarction?",
            "How does insulin regulate blood glucose levels?",
            "What is the mechanism of action for ACE inhibitors?",
            "What are the diagnostic criteria for rheumatoid arthritis?",
            "How does the SARS-CoV-2 virus enter human cells?",
            "What are the main side effects of chemotherapy?",
            "How does the blood-brain barrier function?",
            "What is the pathophysiology of type 2 diabetes?",
            "How do vaccines create immunity?",
            "What are the stages of chronic kidney disease?"
        ]
        
        # Create a dataframe with questions only (answers would be generated by LLMs)
        return pd.DataFrame({
            'question': questions,
            'domain': ['medical'] * len(questions)
        })
    
    def get_samples(self, n: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Get samples from the medical QA dataset.
        
        Args:
            n: Number of samples to return (None for all)
            
        Returns:
            List of samples with prompts
        """
        if self.data is None:
            self.load()
        
        if 'question' in self.data.columns:
            questions = self.data['question'].tolist()
        elif 'question_text' in self.data.columns:
            questions = self.data['question_text'].tolist()
        else:
            raise ValueError("Dataset does not contain question column")
        
        if n is not None:
            questions = questions[:n]
        
        # Create samples with prompts
        samples = []
        for question in questions:
            prompt = self.get_prompt_template().format(question=question)
            samples.append({
                'domain': 'medical',
                'question': question,
                'prompt': prompt
            })
        
        return samples
    
    def get_prompt_template(self) -> str:
        """
        Get the prompt template for medical domain.
        
        Returns:
            Prompt template string
        """
        return "You are a medical expert. Please answer the following medical question accurately and concisely:\n\n{question}"


class LegalQADataset(DomainDataset):
    """Dataset for legal question answering."""
    
    def __init__(self, data_path: Optional[str] = None):
        """
        Initialize the legal QA dataset.
        
        Args:
            data_path: Path to the dataset file (None to use default)
        """
        super().__init__("legal_qa", "legal")
        self.data_path = data_path
    
    def load(self) -> None:
        """Load the legal QA dataset."""
        if self.data_path and os.path.exists(self.data_path):
            # Load from local file if available
            if self.data_path.endswith('.csv'):
                self.data = pd.read_csv(self.data_path)
            elif self.data_path.endswith('.json'):
                with open(self.data_path, 'r') as f:
                    self.data = json.load(f)
            else:
                raise ValueError(f"Unsupported file format: {self.data_path}")
        else:
            # Use synthetic data for legal domain
            self.data = self._create_synthetic_data()
    
    def _create_synthetic_data(self) -> pd.DataFrame:
        """Create synthetic legal QA data for testing."""
        questions = [
            "What constitutes a breach of contract?",
            "How is intellectual property protected under international law?",
            "What are the elements of negligence in tort law?",
            "How does the doctrine of stare decisis function in common law systems?",
            "What rights are protected under the Fourth Amendment?",
            "What is the difference between a patent and a copyright?",
            "How does arbitration differ from litigation?",
            "What constitutes insider trading under securities law?",
            "What are the legal requirements for a valid will?",
            "How does diplomatic immunity work under international law?"
        ]
        
        # Create a dataframe with questions only
        return pd.DataFrame({
            'question': questions,
            'domain': ['legal'] * len(questions)
        })
    
    def get_samples(self, n: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Get samples from the legal QA dataset.
        
        Args:
            n: Number of samples to return (None for all)
            
        Returns:
            List of samples with prompts
        """
        if self.data is None:
            self.load()
        
        questions = self.data['question'].tolist()
        
        if n is not None:
            questions = questions[:n]
        
        # Create samples with prompts
        samples = []
        for question in questions:
            prompt = self.get_prompt_template().format(question=question)
            samples.append({
                'domain': 'legal',
                'question': question,
                'prompt': prompt
            })
        
        return samples
    
    def get_prompt_template(self) -> str:
        """
        Get the prompt template for legal domain.
        
        Returns:
            Prompt template string
        """
        return "You are a legal expert. Please answer the following legal question accurately and concisely:\n\n{question}"


class GeneralKnowledgeDataset(DomainDataset):
    """Dataset for general knowledge question answering."""
    
    def __init__(self, data_path: Optional[str] = None):
        """
        Initialize the general knowledge dataset.
        
        Args:
            data_path: Path to the dataset file (None to use default)
        """
        super().__init__("general_knowledge", "general")
        self.data_path = data_path
    
    def load(self) -> None:
        """Load the general knowledge dataset."""
        if self.data_path and os.path.exists(self.data_path):
            # Load from local file if available
            if self.data_path.endswith('.csv'):
                self.data = pd.read_csv(self.data_path)
            elif self.data_path.endswith('.json'):
                with open(self.data_path, 'r') as f:
                    self.data = json.load(f)
            else:
                raise ValueError(f"Unsupported file format: {self.data_path}")
        else:
            # Use a sample of the TriviaQA dataset from Hugging Face
            try:
                dataset = load_dataset("trivia_qa", "unfiltered", split="train[:100]")
                self.data = dataset.to_pandas()
            except Exception as e:
                # Fallback to synthetic data if dataset loading fails
                print(f"Failed to load TriviaQA dataset: {e}")
                self.data = self._create_synthetic_data()
    
    def _create_synthetic_data(self) -> pd.DataFrame:
        """Create synthetic general knowledge data for testing."""
        questions = [
            "What is the capital of France?",
            "Who wrote the novel '1984'?",
            "What is the chemical symbol for gold?",
            "Which planet is known as the Red Planet?",
            "Who painted the Mona Lisa?",
            "What is the largest ocean on Earth?",
            "What year did World War II end?",
            "What is the tallest mountain in the world?",
            "Who was the first person to step on the moon?",
            "What is the speed of light in a vacuum?"
        ]
        
        # Create a dataframe with questions only
        return pd.DataFrame({
            'question': questions,
            'domain': ['general'] * len(questions)
        })
    
    def get_samples(self, n: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Get samples from the general knowledge dataset.
        
        Args:
            n: Number of samples to return (None for all)
            
        Returns:
            List of samples with prompts
        """
        if self.data is None:
            self.load()
        
        if 'question' in self.data.columns:
            questions = self.data['question'].tolist()
        elif 'question_text' in self.data.columns:
            questions = self.data['question_text'].tolist()
        else:
            raise ValueError("Dataset does not contain question column")
        
        if n is not None:
            questions = questions[:n]
        
        # Create samples with prompts
        samples = []
        for question in questions:
            prompt = self.get_prompt_template().format(question=question)
            samples.append({
                'domain': 'general',
                'question': question,
                'prompt': prompt
            })
        
        return samples
    
    def get_prompt_template(self) -> str:
        """
        Get the prompt template for general knowledge domain.
        
        Returns:
            Prompt template string
        """
        return "Please answer the following general knowledge question accurately and concisely:\n\n{question}"


# Factory function to create domain datasets
def create_domain_dataset(domain: str, data_path: Optional[str] = None) -> DomainDataset:
    """
    Create a domain dataset based on the specified domain.
    
    Args:
        domain: Domain category ('medical', 'legal', 'general')
        data_path: Path to the dataset file (None to use default)
        
    Returns:
        Domain dataset instance
    """
    if domain == "medical":
        return MedicalQADataset(data_path)
    elif domain == "legal":
        return LegalQADataset(data_path)
    elif domain == "general":
        return GeneralKnowledgeDataset(data_path)
    else:
        raise ValueError(f"Unsupported domain: {domain}")