mfq-replication 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ """MFQ-30 Moral Foundation Questionnaire Replication Package.
2
+
3
+ A Python package for analyzing LLM moral values using the MFQ-30 instrument.
4
+ """
5
+
6
+ __version__ = "1.0.0"
7
+ __author__ = "Yichao Jin"
8
+
9
+ from .analyzer import MFQAnalyzer
10
+ from .composite import compute_composites
11
+ from .validator import validate_data
12
+
13
+ __all__ = ['MFQAnalyzer', 'compute_composites', 'validate_data']
@@ -0,0 +1,104 @@
1
+ """MFQ-30 Analyzer."""
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+ from typing import Dict, Optional, Tuple, List
6
+ from .composite import compute_composites, compute_foundation_stats
7
+ from .validator import validate_data
8
+
9
+
10
+ class MFQAnalyzer:
11
+ """Analyzer for MFQ-30 moral foundation questionnaire data."""
12
+
13
+ def __init__(self, data_path: Optional[str] = None):
14
+ """Initialize analyzer.
15
+
16
+ Args:
17
+ data_path: Path to MFQ-30 CSV data file
18
+ """
19
+ self.data_path = data_path
20
+ self.df: Optional[pd.DataFrame] = None
21
+ self.results: Optional[pd.DataFrame] = None
22
+
23
+ def load(self, data_path: str) -> 'MFQAnalyzer':
24
+ """Load data from CSV.
25
+
26
+ Args:
27
+ data_path: Path to CSV file
28
+
29
+ Returns:
30
+ Self for chaining
31
+ """
32
+ self.df = pd.read_csv(data_path)
33
+ self.data_path = data_path
34
+ return self
35
+
36
+ def validate(self) -> Tuple[bool, List[str]]:
37
+ """Validate loaded data.
38
+
39
+ Returns:
40
+ Tuple of (is_valid, error_messages)
41
+ """
42
+ if self.df is None:
43
+ return False, ["No data loaded"]
44
+ return validate_data(self.data_path) if self.data_path else (False, ["No file path"])
45
+
46
+ def analyze(self) -> 'MFQAnalyzer':
47
+ """Run MFQ-30 analysis.
48
+
49
+ Returns:
50
+ Self for chaining
51
+ """
52
+ if self.df is None:
53
+ raise ValueError("No data loaded. Call load() first.")
54
+
55
+ self.results = compute_composites(self.df)
56
+ return self
57
+
58
+ def get_stats(self) -> Dict[str, Dict[str, float]]:
59
+ """Get foundation statistics.
60
+
61
+ Returns:
62
+ Dictionary of foundation statistics
63
+ """
64
+ if self.results is None:
65
+ raise ValueError("No results. Call analyze() first.")
66
+ return compute_foundation_stats(self.results)
67
+
68
+ def summary(self) -> str:
69
+ """Generate text summary of results.
70
+
71
+ Returns:
72
+ Formatted summary string
73
+ """
74
+ if self.results is None:
75
+ return "No results available."
76
+
77
+ stats = self.get_stats()
78
+ lines = [
79
+ "MFQ-30 Moral Foundation Analysis",
80
+ "=" * 40,
81
+ ""
82
+ ]
83
+
84
+ for foundation, stat in stats.items():
85
+ lines.append(f"{foundation.capitalize():12} Mean={stat['mean']:.2f}, SD={stat['sd']:.2f}")
86
+
87
+ if 'mfq_composite' in self.results.columns:
88
+ lines.append("")
89
+ lines.append(f"Overall Composite: {self.results['mfq_composite'].mean():.2f}")
90
+
91
+ lines.append("")
92
+ lines.append(f"N = {len(self.results)} models")
93
+
94
+ return "\n".join(lines)
95
+
96
+ def save_results(self, output_path: str) -> None:
97
+ """Save results to CSV.
98
+
99
+ Args:
100
+ output_path: Output CSV file path
101
+ """
102
+ if self.results is None:
103
+ raise ValueError("No results to save.")
104
+ self.results.to_csv(output_path, index=False)
mfq_replication/cli.py ADDED
@@ -0,0 +1,77 @@
1
+ """MFQ-30 CLI."""
2
+
3
+ import argparse
4
+ import sys
5
+ from .analyzer import MFQAnalyzer
6
+ from . import __version__
7
+
8
+
9
+ def main():
10
+ """Main CLI entry point."""
11
+ parser = argparse.ArgumentParser(
12
+ description='MFQ-30 Moral Foundation Questionnaire Analyzer',
13
+ prog='mfq-analyze'
14
+ )
15
+ parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
16
+
17
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
18
+
19
+ # Analyze command
20
+ analyze_parser = subparsers.add_parser('analyze', help='Analyze MFQ-30 data')
21
+ analyze_parser.add_argument('input', help='Input CSV file')
22
+ analyze_parser.add_argument('-o', '--output', help='Output CSV file')
23
+
24
+ # Validate command
25
+ validate_parser = subparsers.add_parser('validate', help='Validate MFQ-30 data')
26
+ validate_parser.add_argument('input', help='Input CSV file')
27
+
28
+ # Info command
29
+ subparsers.add_parser('info', help='Show MFQ-30 information')
30
+
31
+ args = parser.parse_args()
32
+
33
+ if args.command == 'analyze':
34
+ analyzer = MFQAnalyzer()
35
+ analyzer.load(args.input)
36
+
37
+ is_valid, errors = analyzer.validate()
38
+ if not is_valid:
39
+ print(f"Validation failed: {errors}", file=sys.stderr)
40
+ sys.exit(1)
41
+
42
+ analyzer.analyze()
43
+ print(analyzer.summary())
44
+
45
+ if args.output:
46
+ analyzer.save_results(args.output)
47
+ print(f"\nResults saved to: {args.output}")
48
+
49
+ elif args.command == 'validate':
50
+ is_valid, errors = MFQAnalyzer().load(args.input).validate()
51
+ if is_valid:
52
+ print("✓ Data format is valid")
53
+ else:
54
+ print("✗ Validation failed:")
55
+ for error in errors:
56
+ print(f" - {error}")
57
+ sys.exit(1)
58
+
59
+ elif args.command == 'info':
60
+ print("MFQ-30 Moral Foundation Questionnaire")
61
+ print("=" * 40)
62
+ print("\nFive moral dimensions:")
63
+ print(" 1. Care/Harm - Concern for caring vs. harming")
64
+ print(" 2. Fairness/Cheating - Concern for fairness vs. cheating")
65
+ print(" 3. Loyalty/Betrayal - Concern for loyalty vs. betrayal")
66
+ print(" 4. Authority/Subversion - Concern for authority vs. subversion")
67
+ print(" 5. Sanctity/Degradation - Concern for sanctity vs. degradation")
68
+ print("\nData format:")
69
+ print(" - CSV with columns: model_id, q1, q2, ..., q30")
70
+ print(" - Responses: 0-5 (0=Strongly Disagree, 5=Strongly Agree)")
71
+
72
+ else:
73
+ parser.print_help()
74
+
75
+
76
+ if __name__ == '__main__':
77
+ main()
@@ -0,0 +1,59 @@
1
+ """MFQ-30 Composite Score Calculator."""
2
+
3
+ import pandas as pd
4
+ import numpy as np
5
+ from typing import Dict
6
+
7
+
8
+ # MFQ-30 item mapping to foundations
9
+ FOUNDATIONS = {
10
+ 'care': [1, 2, 7, 13, 14, 20, 21, 28],
11
+ 'fairness': [3, 4, 8, 15, 16, 22, 23, 29],
12
+ 'loyalty': [5, 9, 10, 17, 24, 25, 30],
13
+ 'authority': [6, 11, 12, 18, 19, 26, 27],
14
+ 'sanctity': [31, 32] # Note: MFQ-30 has 30 items, sanctity subset
15
+ }
16
+
17
+
18
+ def compute_composites(df: pd.DataFrame) -> pd.DataFrame:
19
+ """Compute MFQ-30 moral foundation composites.
20
+
21
+ Args:
22
+ df: DataFrame with q1-q30 columns
23
+
24
+ Returns:
25
+ DataFrame with computed composite scores
26
+ """
27
+ result = df.copy()
28
+
29
+ # Calculate foundation scores (mean of relevant items)
30
+ for foundation, items in FOUNDATIONS.items():
31
+ cols = [f'q{i}' for i in items if f'q{i}' in df.columns]
32
+ if cols:
33
+ result[f'{foundation}_raw'] = df[cols].mean(axis=1)
34
+
35
+ # Calculate overall composite
36
+ composite_cols = [c for c in result.columns if c.endswith('_raw')]
37
+ if composite_cols:
38
+ result['mfq_composite'] = result[composite_cols].mean(axis=1)
39
+
40
+ return result
41
+
42
+
43
+ def compute_foundation_stats(df: pd.DataFrame) -> Dict[str, Dict[str, float]]:
44
+ """Compute descriptive statistics for each foundation.
45
+
46
+ Returns:
47
+ Dictionary of foundation -> {mean, sd, min, max}
48
+ """
49
+ stats = {}
50
+ for foundation in ['care', 'fairness', 'loyalty', 'authority', 'sanctity']:
51
+ col = f'{foundation}_raw'
52
+ if col in df.columns:
53
+ stats[foundation] = {
54
+ 'mean': df[col].mean(),
55
+ 'sd': df[col].std(),
56
+ 'min': df[col].min(),
57
+ 'max': df[col].max()
58
+ }
59
+ return stats
@@ -0,0 +1,37 @@
1
+ """MFQ-30 Data Validator."""
2
+
3
+ import pandas as pd
4
+ from typing import Tuple, List
5
+
6
+
7
+ def validate_data(filepath: str) -> Tuple[bool, List[str]]:
8
+ """Validate MFQ-30 data file format.
9
+
10
+ Args:
11
+ filepath: Path to CSV file
12
+
13
+ Returns:
14
+ Tuple of (is_valid, error_messages)
15
+ """
16
+ errors = []
17
+
18
+ try:
19
+ df = pd.read_csv(filepath)
20
+ except Exception as e:
21
+ return False, [f"Cannot read file: {e}"]
22
+
23
+ # Check required columns
24
+ required = ['model_id'] + [f'q{i}' for i in range(1, 31)]
25
+ missing = [col for col in required if col not in df.columns]
26
+
27
+ if missing:
28
+ errors.append(f"Missing columns: {missing}")
29
+
30
+ # Check value ranges (0-5)
31
+ for col in [c for c in df.columns if c.startswith('q')]:
32
+ if col in df.columns:
33
+ invalid = df[(df[col] < 0) | (df[col] > 5)][col]
34
+ if len(invalid) > 0:
35
+ errors.append(f"Column {col} has values outside 0-5 range")
36
+
37
+ return len(errors) == 0, errors
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: mfq-replication
3
+ Version: 1.0.0
4
+ Summary: MFQ-30 Moral Foundation Questionnaire replication package
5
+ Author-email: Yichao Jin <jyc20220303@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/yichao2022/value-sensitivity-llm-audit
8
+ Project-URL: Repository, https://github.com/yichao2022/value-sensitivity-llm-audit
9
+ Keywords: mfq,moral-foundation,llm,psychology,replication
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: pandas>=1.5.0
22
+ Requires-Dist: numpy>=1.21.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.0; extra == "dev"
25
+ Requires-Dist: black>=22.0; extra == "dev"
26
+
27
+ # MFQ-30 Replication Package
28
+
29
+ Python package for replicating the MFQ-30 (Moral Foundation Questionnaire-30) analysis from Jin (2026).
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install mfq-replication
35
+ ```
36
+
37
+ ## Quick Start
38
+
39
+ ```python
40
+ from mfq_replication import MFQAnalyzer
41
+
42
+ # Load and analyze data
43
+ analyzer = MFQAnalyzer()
44
+ analyzer.load("mfq30_data.csv").analyze()
45
+
46
+ # Get summary
47
+ print(analyzer.summary())
48
+
49
+ # Save results
50
+ analyzer.save_results("results.csv")
51
+ ```
52
+
53
+ ## CLI Usage
54
+
55
+ ```bash
56
+ # Analyze data
57
+ mfq-analyze analyze data.csv --output results.csv
58
+
59
+ # Validate format
60
+ mfq-analyze validate data.csv
61
+
62
+ # Show info
63
+ mfq-analyze info
64
+ ```
65
+
66
+ ## Data Format
67
+
68
+ CSV with columns:
69
+ - `model_id`: Model identifier
70
+ - `q1` to `q30`: MFQ-30 responses (0-5 scale)
71
+
72
+ ## About MFQ-30
73
+
74
+ The Moral Foundation Questionnaire-30 measures five moral dimensions:
75
+ - **Care/Harm**: Concern for caring vs. harming
76
+ - **Fairness/Cheating**: Concern for fairness vs. cheating
77
+ - **Loyalty/Betrayal**: Concern for loyalty vs. betrayal
78
+ - **Authority/Subversion**: Concern for authority vs. subversion
79
+ - **Sanctity/Degradation**: Concern for sanctity vs. degradation
80
+
81
+ ## Citation
82
+
83
+ Jin, Y. (2026). LLM Value Sensitivity: Replication Package.
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,10 @@
1
+ mfq_replication/__init__.py,sha256=GzJnOxOYlyxVGOQGfDqaWADKskqNkCEP3rzVjg36N1w,373
2
+ mfq_replication/analyzer.py,sha256=mjZU8n0Xn-dSLZ3bwh8EWd6CY5ESbrpZ-x1H_9djYcQ,3109
3
+ mfq_replication/cli.py,sha256=5ruEp9zetfx_YO5ES-E0Mb8dAvw16ZxTBnY_ffAlnQo,2631
4
+ mfq_replication/composite.py,sha256=q_JgYHbPJq3zoCWQJbfDRCsFj8xRF-WMfw9vC_eCyjM,1767
5
+ mfq_replication/validator.py,sha256=fjGGWRKL7dRXt2Ii9AlhS0XGXICGnJxQ8Osn5X0FWi0,1022
6
+ mfq_replication-1.0.0.dist-info/METADATA,sha256=HA0SfF7ODptQzKyMpc4280luvSFh__zqMwHKig1B5XY,2282
7
+ mfq_replication-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ mfq_replication-1.0.0.dist-info/entry_points.txt,sha256=8ZhtaOcvcirE9E9HoQ8IbyJ0Fc2NanF8C16Fn7rZMKo,57
9
+ mfq_replication-1.0.0.dist-info/top_level.txt,sha256=jbheuujcTK9OCcPMpY1WZ8fA3DLnHbxei1xFwmSO00Q,16
10
+ mfq_replication-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mfq-analyze = mfq_replication.cli:main
@@ -0,0 +1 @@
1
+ mfq_replication