metacountregressor 0.1.111__tar.gz → 0.1.115__tar.gz

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.
Files changed (28) hide show
  1. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/PKG-INFO +19 -5
  2. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/app_main.py +9 -4
  3. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/helperprocess.py +267 -5
  4. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/main.py +172 -61
  5. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/metaheuristics.py +20 -9
  6. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/setup.py +3 -2
  7. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/solution.py +483 -131
  8. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor.egg-info/PKG-INFO +19 -5
  9. metacountregressor-0.1.115/metacountregressor.egg-info/requires.txt +8 -0
  10. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/setup.py +17 -6
  11. metacountregressor-0.1.111/metacountregressor.egg-info/requires.txt +0 -3
  12. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/LICENSE.txt +0 -0
  13. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/README.rst +0 -0
  14. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/__init__.py +0 -0
  15. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/_device_cust.py +0 -0
  16. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/data_split_helper.py +0 -0
  17. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/halton.py +0 -0
  18. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/main_old.py +0 -0
  19. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/pareto_file.py +0 -0
  20. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/pareto_logger__plot.py +0 -0
  21. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/single_objective_finder.py +0 -0
  22. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor/test_generated_paper2.py +0 -0
  23. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor.egg-info/SOURCES.txt +0 -0
  24. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor.egg-info/dependency_links.txt +0 -0
  25. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor.egg-info/not-zip-safe +0 -0
  26. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/metacountregressor.egg-info/top_level.txt +0 -0
  27. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/setup.cfg +0 -0
  28. {metacountregressor-0.1.111 → metacountregressor-0.1.115}/tests/test.py +0 -0
@@ -1,17 +1,31 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: metacountregressor
3
- Version: 0.1.111
4
- Summary: Extensions for a Python package for estimation of count models.
3
+ Version: 0.1.115
4
+ Summary: Extensive Testing for Estimation of Data Count Models
5
5
  Home-page: https://github.com/zahern/CountDataEstimation
6
6
  Author: Zeke Ahern
7
- Author-email: zeke.ahern@hdr.qut.edu.au
8
- License: QUT
7
+ Author-email: z.ahern@qut.edu.au
8
+ License: MIT
9
9
  Requires-Python: >=3.10
10
10
  Description-Content-Type: text/markdown
11
11
  License-File: LICENSE.txt
12
12
  Requires-Dist: numpy>=1.13.1
13
13
  Requires-Dist: scipy>=1.0.0
14
14
  Requires-Dist: requests
15
+ Requires-Dist: latextable
16
+ Requires-Dist: pandas
17
+ Requires-Dist: scikit_learn>=1.4.1.post1
18
+ Requires-Dist: statsmodels
19
+ Requires-Dist: psutil
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license
26
+ Dynamic: requires-dist
27
+ Dynamic: requires-python
28
+ Dynamic: summary
15
29
 
16
30
  <div style="display: flex; align-items: center;">
17
31
  <img src="https://github.com/zahern/data/raw/main/m.png" alt="My Image" style="width: 100px; margin-right: 20px;">
@@ -69,15 +69,20 @@ def main(args, **kwargs):
69
69
  #data_info['data']['Group'][0]
70
70
  #data_info['data']['Panel'][0]
71
71
  args['decisions'] = data_info['analyst']
72
-
73
- if not np.isnan(data_info['data']['Grouped'][0]):
72
+ grouped_c = data_info['data']['Grouped'][0]
73
+ if isinstance(data_info['data']['Grouped'][0],str):
74
74
  args['group'] = data_info['data']['Grouped'][0]
75
- args['ID'] = data_info['data']['Grouped'][0]
76
- if not np.isnan(data_info['data']['Panel'][0]):
75
+ args['ID'] = data_info['data']['Panel'][0]
76
+ if isinstance(data_info['data']['Panel'][0],str):
77
77
  args['panels'] = data_info['data']['Panel'][0]
78
78
 
79
79
  df = pd.read_csv(str(data_info['data']['Problem'][0]))
80
80
  x_df = df.drop(columns=[data_info['data']['Y'][0]])
81
+ # drop the columns of x_df where column is string exclude the column stype args['group']
82
+ exclude_column = args['group']
83
+ columns_to_keep = x_df.dtypes != 'object'
84
+ columns_to_keep |= (x_df.columns == exclude_column)
85
+ x_df = x_df.loc[:, columns_to_keep]
81
86
  y_df = df[[data_info['data']['Y'][0]]]
82
87
  y_df.rename(columns={data_info['data']['Y'][0]: "Y"}, inplace=True)
83
88
 
@@ -1,10 +1,28 @@
1
+ from os.path import exists
1
2
  import numpy as np
2
3
  import pandas as pd
3
4
  import csv
4
5
  import matplotlib.pyplot as plt
6
+ from scipy import stats as st
7
+ from sklearn.preprocessing import StandardScaler
8
+
5
9
 
6
10
  plt.style.use('https://github.com/dhaitz/matplotlib-stylesheets/raw/master/pitayasmoothie-dark.mplstyle')
7
11
 
12
+
13
+
14
+
15
+
16
+ from itertools import product
17
+
18
+ # Function to create a list of dictionaries from a parameter grid
19
+ def generate_param_combinations(param_grid):
20
+ keys = param_grid.keys()
21
+ values = param_grid.values()
22
+ combinations = [dict(zip(keys, v)) for v in product(*values)]
23
+ return combinations
24
+
25
+
8
26
  ##Select the best Features Based on RF
9
27
  def select_features(X_train, y_train, n_f=16):
10
28
  try:
@@ -77,6 +95,7 @@ def findCorrelation(corr, cutoff=0.9, exact=None): """
77
95
  findCorrelation(R1, cutoff=0.6, exact=True) # ['x1', 'x5', 'x4']
78
96
  """
79
97
 
98
+
80
99
  def _findCorrelation_fast(corr, avg, cutoff):
81
100
 
82
101
  combsAboveCutoff = corr.where(lambda x: (np.tril(x) == 0) & (x > cutoff)).stack().index
@@ -151,6 +170,230 @@ def remove_files(yes=1):
151
170
  os.remove('pop_log.csv')
152
171
 
153
172
 
173
+ # Function to process the DataFrame
174
+ '''
175
+ Example usuage
176
+ # Configuration dictionary
177
+ config = {
178
+ 'Age': {
179
+ 'type': 'bin',
180
+ 'bins': [0, 18, 35, 50, 100],
181
+ 'labels': ['Child', 'YoungAdult', 'MiddleAged', 'Senior'],
182
+ 'prefix': 'Age_Binned'
183
+ },
184
+ 'Income': {
185
+ 'type': 'bin',
186
+ 'bins': [0, 2000, 5000, 10000],
187
+ 'labels': ['Low', 'Medium', 'High'],
188
+ 'prefix': 'Income_Binned'
189
+ },
190
+ 'Gender': {
191
+ 'type': 'one-hot',
192
+ 'prefix': 'Gender'
193
+ },
194
+ 'Score': {
195
+ 'type': 'none'
196
+ }
197
+ }
198
+ '''
199
+ def null_handler(vari):
200
+ if vari in locals():
201
+ return vari
202
+ else:
203
+ print(f'{vari} does not exist, setting None..')
204
+ return None
205
+
206
+
207
+ def set_up_analyst_constraints(data_characteristic, model_terms, variable_decisions_alt = None):
208
+
209
+
210
+ name_data_characteristics = data_characteristic.columns.tolist()
211
+ # Get non-None values as a list
212
+ non_none_terms = [value for value in model_terms.values() if value is not None]
213
+ # how to make name_data_characteristics - non_none_terms
214
+
215
+ result = [item for item in name_data_characteristics if item not in non_none_terms]
216
+ distu = ['normal', 'uniform', 'triangular']
217
+ tra = ['no', 'sqrt', 'arcsinh']
218
+ if model_terms.get('group') is None:
219
+ print('cant have grouped rpm, removing level 4 from every item')
220
+ MAKE_ALL_4_FALSE = True
221
+ else:
222
+ MAKE_ALL_4_FALSE = False
223
+
224
+ variable_decisions = {
225
+ name: {
226
+ 'levels': list(range(6)),
227
+ 'Distributions': distu,
228
+ 'Transformations': tra
229
+ }
230
+ for name in result
231
+ }
232
+ # Override elements in the original dictionary with the alt dictionary
233
+ if variable_decisions_alt is not None:
234
+ for key, alt_value in variable_decisions_alt.items():
235
+ if key in variable_decisions:
236
+ # Update the existing entry
237
+ variable_decisions[key].update(alt_value)
238
+ else:
239
+ # Add new entry if it doesn't exist
240
+ variable_decisions[key] = alt_value
241
+ # Prepare the data for the DataFrame
242
+ rows = []
243
+ for column_name, details in variable_decisions.items():
244
+ # Create a row dictionary
245
+ row = {'Column': column_name}
246
+
247
+ # Add levels as True/False for Level 0 through Level 5
248
+ for level in range(6): # Assuming Level 0 to Level 5
249
+
250
+ if level == 4 and MAKE_ALL_4_FALSE:
251
+ row[f'Level {level}'] = False
252
+ else:
253
+ row[f'Level {level}'] = level in details['levels']
254
+
255
+ # Add distributions and transformations directly
256
+
257
+ # Add distributions and transformations as comma-separated strings
258
+ row['Distributions'] = str(details['Distributions'])
259
+ row['Transformations'] = str(details['Transformations'])
260
+
261
+ rows.append(row)
262
+
263
+ # Create the DataFrame
264
+ df = pd.DataFrame(rows)
265
+
266
+ data_new = data_characteristic.rename(columns={v: k for k, v in model_terms.items() if v in data_characteristic.columns})
267
+ return df, data_new
268
+
269
+ # Function to guess Low, Medium, High ranges
270
+ def guess_low_medium_high(column_name, series):
271
+ # Compute the tertiles (33rd and 66th percentiles)
272
+ #print('did it make it...')
273
+ #mode_value = st.mode(series) # Get the most frequent value
274
+ #i dont think this works cayse its not a seriers any other way
275
+ is_binary = series.isin([0, 1]).all()
276
+ if is_binary:
277
+ return {
278
+ 'type': 'binary',
279
+ 'bins': [0,1],
280
+ 'labels': ['Off', 'On'],
281
+ 'prefix': f'{column_name}'
282
+
283
+ }
284
+
285
+ # series = pd.to_numeric(series, errors='coerce').fillna(mode_value)
286
+ low_threshold = np.quantile(series, 0.33)
287
+ high_threshold = np.quantile(series,0.66)
288
+
289
+ # Define the bins and labels
290
+ bins = [np.min(series) - 1, low_threshold, high_threshold, np.max(series)]
291
+ # Handle duplicate bins by adjusting labels
292
+ if len(set(bins)) < len(bins): # Check for duplicate bin edges
293
+ if low_threshold == high_threshold:
294
+ # Collapse to two bins (Low and High)
295
+ bins = [np.min(series) - 1, low_threshold, np.max(series)]
296
+ labels = ['Low', 'High']
297
+ else:
298
+ # Collapse to three unique bins
299
+ bins = sorted(set(bins)) # Remove duplicate edges
300
+ labels = [f'Bin {i + 1}' for i in range(len(bins) - 1)]
301
+ else:
302
+ # Standard case: Low, Medium, High
303
+ labels = ['Low', 'Medium', 'High']
304
+
305
+ return {
306
+ 'type': 'bin',
307
+ 'bins': bins,
308
+ 'labels': labels,
309
+ 'prefix': f'{column_name}'
310
+ }
311
+
312
+ def transform_dataframe(df, config):
313
+ output_df = pd.DataFrame()
314
+
315
+ for column, settings in config.items():
316
+ if settings['type'] == 'bin':
317
+ # Apply binning
318
+ # Get unique bins (remove duplicates)
319
+ unique_bins = sorted(set(settings['bins']))
320
+
321
+ # Adjust labels if necessary
322
+ if len(unique_bins) - 1 != len(settings['labels']):
323
+ print(f"Adjusting labels to match bins: {len(unique_bins) - 1} bins detected.")
324
+ labels = [f'Bin {i+1}' for i in range(len(unique_bins) - 1)]
325
+ else:
326
+ labels = settings['labels']
327
+
328
+ # Perform the binning
329
+ binned_d = pd.cut(
330
+ df[column],
331
+ bins=unique_bins, # Deduplicated bins
332
+ labels=labels, # Adjusted or original labels
333
+ right=False # Adjust based on whether to include the right edge
334
+ )
335
+ # One-hot encode the binned column
336
+ binned_dummies = pd.get_dummies(binned_d, prefix=settings['prefix'])
337
+ output_df = pd.concat([output_df, binned_dummies], axis=1)
338
+
339
+ elif settings['type'] == 'one-hot':
340
+ # One-hot encode the column
341
+ one_hot_dummies = pd.get_dummies(df[column], prefix=settings.get('prefix', column))
342
+ output_df = pd.concat([output_df, one_hot_dummies], axis=1)
343
+
344
+ elif settings['type'] == 'continuous':
345
+ # Apply function to continuous data
346
+ data = df[column]
347
+ if 'bounds' in settings:
348
+ # Apply bounds filtering
349
+ lower, upper = settings['bounds']
350
+ data = data[(data >= lower) & (data <= upper)]
351
+ if 'apply_func' in settings:
352
+ # Apply custom function
353
+ data = data.apply(settings['apply_func'])
354
+ output_df[column] = data
355
+
356
+ elif settings['type'] == 'none':
357
+ # Leave the column unchanged
358
+ if column in df.columns:
359
+
360
+ output_df = pd.concat([output_df, df[[column]]], axis=1)
361
+ else:
362
+ print(f'config variable {column} is not in the data. Ignoring ...')
363
+ return output_df
364
+
365
+ # Helper function to guess column type and update `config`
366
+ def guess_column_type(column_name, series):
367
+
368
+ if series.empty:
369
+ raise ValueError(f"The column {column_name} contains no numeric data.")
370
+
371
+ if series.dtype == 'object' or series.dtype.name == 'category':
372
+ # If the column is categorical (e.g., strings), assume one-hot encoding
373
+ return {'type': 'one-hot', 'prefix': column_name}
374
+ elif pd.api.types.is_numeric_dtype(series):
375
+ unique_values = series.nunique()
376
+
377
+ if unique_values < 5:
378
+ return {'type': 'one-hot', 'prefix': column_name}
379
+
380
+ elif np.max(series) - np.min(series) > 20:
381
+ print('made it through here')
382
+ # If there are few unique values, assume binning with default bins
383
+ return guess_low_medium_high(column_name,series)
384
+ else:
385
+ # # Otherwise, assume continuous data with normalization
386
+ # Otherwise, fallback to continuous standardization
387
+ return {
388
+ 'type': 'continuous',
389
+ 'apply_func': (lambda x: (x - series.mean()) / series.std()) # Z-Score Standardization
390
+ }
391
+ else:
392
+ # Default fallback (leave the column unchanged)
393
+ return {'type': 'none'}
394
+
395
+
396
+
154
397
  def as_wide_factor(x_df, yes=1, min_factor=2, max_factor=8, keep_original=0, exclude=[]):
155
398
  if not yes:
156
399
  return x_df
@@ -173,7 +416,7 @@ def PCA_code(X, n_components=5):
173
416
 
174
417
 
175
418
  def interactions(df, keep=None, drop_this_perc=0.6, interact = False):
176
-
419
+ full_columns = df.columns
177
420
  if interact:
178
421
  interactions_list = []
179
422
  for i, var_i in enumerate(df.columns):
@@ -199,14 +442,31 @@ def interactions(df, keep=None, drop_this_perc=0.6, interact = False):
199
442
  df = pd.concat([df, df_interactions], axis=1, sort=False)
200
443
 
201
444
  # second
202
- corr_matrix = df.corr().abs()
445
+ # Remove `keep` columns from the correlation matrix
446
+ if keep is not None:
447
+ missing_columns = [col for col in keep if col not in df.columns]
448
+
449
+ if missing_columns:
450
+ print(f"The following columns are not in the DataFrame and will be ignored: {missing_columns}")
451
+ keep = [col for col in keep if col not in missing_columns]
452
+ df_corr = df.drop(columns=keep, errors='ignore', inplace=False) # Exclude `keep` columns
453
+ else:
454
+ df_corr = df
455
+
456
+ # Compute the absolute correlation matrix
457
+ corr_matrix = df_corr.corr().abs()
458
+
459
+ # Keep only the upper triangle of the correlation matrix
203
460
  upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))
204
461
 
205
- # Find features with correlation greater than 0.6
462
+ # Find features with correlation greater than the threshold
206
463
  to_drop = [column for column in upper.columns if any(upper[column] > drop_this_perc)]
464
+
465
+ # Ensure `keep` columns are not dropped
207
466
  if keep is not None:
208
- to_drop = [column for column in to_drop if column not in keep]
209
- # Drop features
467
+ to_drop = [column for column in to_drop if column not in full_columns]
468
+
469
+ # Drop the identified features
210
470
  df.drop(to_drop, axis=1, inplace=True)
211
471
 
212
472
  return df
@@ -330,3 +590,5 @@ def entries_to_remove(entries, the_dict):
330
590
  for key in entries:
331
591
  if key in the_dict:
332
592
  del the_dict[key]
593
+
594
+