tsadmetrics 0.1.4__py3-none-any.whl → 0.1.5__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.
Files changed (48) hide show
  1. entorno/bin/activate_this.py +32 -0
  2. entorno/bin/rst2html.py +23 -0
  3. entorno/bin/rst2html4.py +26 -0
  4. entorno/bin/rst2html5.py +33 -0
  5. entorno/bin/rst2latex.py +26 -0
  6. entorno/bin/rst2man.py +27 -0
  7. entorno/bin/rst2odt.py +28 -0
  8. entorno/bin/rst2odt_prepstyles.py +20 -0
  9. entorno/bin/rst2pseudoxml.py +23 -0
  10. entorno/bin/rst2s5.py +24 -0
  11. entorno/bin/rst2xetex.py +27 -0
  12. entorno/bin/rst2xml.py +23 -0
  13. entorno/bin/rstpep2html.py +25 -0
  14. experiments/scripts/compute_metrics.py +187 -0
  15. experiments/scripts/metrics_complexity_analysis.py +109 -0
  16. experiments/scripts/metro_experiment.py +133 -0
  17. experiments/scripts/opt_metro_experiment.py +343 -0
  18. tests/__init__.py +0 -0
  19. tests/test_binary.py +759 -0
  20. tests/test_non_binary.py +371 -0
  21. tsadmetrics/_tsadeval/affiliation/__init__.py +0 -0
  22. tsadmetrics/_tsadeval/affiliation/_affiliation_zone.py +86 -0
  23. tsadmetrics/_tsadeval/affiliation/_integral_interval.py +464 -0
  24. tsadmetrics/_tsadeval/affiliation/_single_ground_truth_event.py +68 -0
  25. tsadmetrics/_tsadeval/affiliation/generics.py +135 -0
  26. tsadmetrics/_tsadeval/affiliation/metrics.py +114 -0
  27. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/File_IO.py +175 -0
  28. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Range.py +50 -0
  29. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Time_Plot.py +184 -0
  30. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/__init__.py +0 -0
  31. tsadmetrics/_tsadeval/eTaPR_pkg/__init__.py +0 -0
  32. tsadmetrics/_tsadeval/eTaPR_pkg/etapr.py +386 -0
  33. tsadmetrics/_tsadeval/eTaPR_pkg/tapr.py +362 -0
  34. tsadmetrics/_tsadeval/prts/__init__.py +0 -0
  35. tsadmetrics/_tsadeval/prts/base/__init__.py +0 -0
  36. tsadmetrics/_tsadeval/prts/base/time_series_metrics.py +165 -0
  37. tsadmetrics/_tsadeval/prts/basic_metrics_ts.py +121 -0
  38. tsadmetrics/_tsadeval/prts/time_series_metrics/__init__.py +0 -0
  39. tsadmetrics/_tsadeval/prts/time_series_metrics/fscore.py +61 -0
  40. tsadmetrics/_tsadeval/prts/time_series_metrics/precision.py +86 -0
  41. tsadmetrics/_tsadeval/prts/time_series_metrics/precision_recall.py +21 -0
  42. tsadmetrics/_tsadeval/prts/time_series_metrics/recall.py +85 -0
  43. {tsadmetrics-0.1.4.dist-info → tsadmetrics-0.1.5.dist-info}/METADATA +1 -1
  44. tsadmetrics-0.1.5.dist-info/RECORD +62 -0
  45. tsadmetrics-0.1.5.dist-info/top_level.txt +4 -0
  46. tsadmetrics-0.1.4.dist-info/RECORD +0 -20
  47. tsadmetrics-0.1.4.dist-info/top_level.txt +0 -1
  48. {tsadmetrics-0.1.4.dist-info → tsadmetrics-0.1.5.dist-info}/WHEEL +0 -0
@@ -0,0 +1,32 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Activate virtualenv for current interpreter:
3
+
4
+ Use exec(open(this_file).read(), {'__file__': this_file}).
5
+
6
+ This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
7
+ """
8
+ import os
9
+ import site
10
+ import sys
11
+
12
+ try:
13
+ abs_file = os.path.abspath(__file__)
14
+ except NameError:
15
+ raise AssertionError("You must use exec(open(this_file).read(), {'__file__': this_file}))")
16
+
17
+ bin_dir = os.path.dirname(abs_file)
18
+ base = bin_dir[: -len("bin") - 1] # strip away the bin part from the __file__, plus the path separator
19
+
20
+ # prepend bin to PATH (this file is inside the bin directory)
21
+ os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep))
22
+ os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
23
+
24
+ # add the virtual environments libraries to the host python import mechanism
25
+ prev_length = len(sys.path)
26
+ for lib in "../lib/python3.8/site-packages".split(os.pathsep):
27
+ path = os.path.realpath(os.path.join(bin_dir, lib))
28
+ site.addsitedir(path.decode("utf-8") if "" else path)
29
+ sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
30
+
31
+ sys.real_prefix = sys.prefix
32
+ sys.prefix = base
@@ -0,0 +1,23 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2html.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing HTML.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline, default_description
18
+
19
+
20
+ description = ('Generates (X)HTML documents from standalone reStructuredText '
21
+ 'sources. ' + default_description)
22
+
23
+ publish_cmdline(writer_name='html', description=description)
@@ -0,0 +1,26 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2html4.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing (X)HTML.
9
+
10
+ The output conforms to XHTML 1.0 transitional
11
+ and almost to HTML 4.01 transitional (except for closing empty tags).
12
+ """
13
+
14
+ try:
15
+ import locale
16
+ locale.setlocale(locale.LC_ALL, '')
17
+ except Exception:
18
+ pass
19
+
20
+ from docutils.core import publish_cmdline, default_description
21
+
22
+
23
+ description = ('Generates (X)HTML documents from standalone reStructuredText '
24
+ 'sources. ' + default_description)
25
+
26
+ publish_cmdline(writer_name='html4', description=description)
@@ -0,0 +1,33 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+ # :Copyright: © 2015 Günter Milde.
3
+ # :License: Released under the terms of the `2-Clause BSD license`_, in short:
4
+ #
5
+ # Copying and distribution of this file, with or without modification,
6
+ # are permitted in any medium without royalty provided the copyright
7
+ # notice and this notice are preserved.
8
+ # This file is offered as-is, without any warranty.
9
+ #
10
+ # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
11
+ #
12
+ # Revision: $Revision: 9021 $
13
+ # Date: $Date: 2022-03-04 16:54:22 +0100 (Fr, 04. Mär 2022) $
14
+
15
+ """
16
+ A minimal front end to the Docutils Publisher, producing HTML 5 documents.
17
+
18
+ The output is also valid XML.
19
+ """
20
+
21
+ try:
22
+ import locale # module missing in Jython
23
+ locale.setlocale(locale.LC_ALL, '')
24
+ except locale.Error:
25
+ pass
26
+
27
+ from docutils.core import publish_cmdline, default_description
28
+
29
+ description = ('Generates HTML5 documents from standalone '
30
+ 'reStructuredText sources.\n'
31
+ + default_description)
32
+
33
+ publish_cmdline(writer_name='html5', description=description)
@@ -0,0 +1,26 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2latex.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing LaTeX.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline
18
+
19
+ description = ('Generates LaTeX documents from standalone reStructuredText '
20
+ 'sources. '
21
+ 'Reads from <source> (default is stdin) and writes to '
22
+ '<destination> (default is stdout). See '
23
+ '<https://docutils.sourceforge.io/docs/user/latex.html> for '
24
+ 'the full reference.')
25
+
26
+ publish_cmdline(writer_name='latex', description=description)
entorno/bin/rst2man.py ADDED
@@ -0,0 +1,27 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # Author:
4
+ # Contact: grubert@users.sf.net
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ man.py
9
+ ======
10
+
11
+ This module provides a simple command line interface that uses the
12
+ man page writer to output from ReStructuredText source.
13
+ """
14
+
15
+ import locale
16
+ try:
17
+ locale.setlocale(locale.LC_ALL, '')
18
+ except Exception:
19
+ pass
20
+
21
+ from docutils.core import publish_cmdline, default_description
22
+ from docutils.writers import manpage
23
+
24
+ description = ("Generates plain unix manual documents. "
25
+ + default_description)
26
+
27
+ publish_cmdline(writer=manpage.Writer(), description=description)
entorno/bin/rst2odt.py ADDED
@@ -0,0 +1,28 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2odt.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: Dave Kuhlman <dkuhlman@rexx.com>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A front end to the Docutils Publisher, producing OpenOffice documents.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline_to_binary, default_description
18
+ from docutils.writers.odf_odt import Writer, Reader
19
+
20
+
21
+ description = ('Generates OpenDocument/OpenOffice/ODF documents from '
22
+ 'standalone reStructuredText sources. ' + default_description)
23
+
24
+
25
+ writer = Writer()
26
+ reader = Reader()
27
+ output = publish_cmdline_to_binary(reader=reader, writer=writer,
28
+ description=description)
@@ -0,0 +1,20 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # Copyright: This module has been placed in the public domain.
4
+
5
+ """
6
+ Adapt a word-processor-generated styles.odt for odtwriter use:
7
+
8
+ Drop page size specifications from styles.xml in STYLE_FILE.odt.
9
+ See https://docutils.sourceforge.io/docs/user/odt.html#page-size
10
+
11
+ Provisional backwards compatibility stub (to be removed in Docutils >= 0.21).
12
+
13
+ The actual code moved to the "docutils" library package and can be started
14
+ with ``python -m docutils.writers.odf_odt.prepstyles``.
15
+ """
16
+
17
+ from docutils.writers.odf_odt import prepstyles
18
+
19
+ if __name__ == '__main__':
20
+ prepstyles.main()
@@ -0,0 +1,23 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2pseudoxml.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing pseudo-XML.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline, default_description
18
+
19
+
20
+ description = ('Generates pseudo-XML from standalone reStructuredText '
21
+ 'sources (for testing purposes). ' + default_description)
22
+
23
+ publish_cmdline(description=description)
entorno/bin/rst2s5.py ADDED
@@ -0,0 +1,24 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2s5.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: Chris Liechti <cliechti@gmx.net>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing HTML slides using
9
+ the S5 template system.
10
+ """
11
+
12
+ try:
13
+ import locale
14
+ locale.setlocale(locale.LC_ALL, '')
15
+ except Exception:
16
+ pass
17
+
18
+ from docutils.core import publish_cmdline, default_description
19
+
20
+
21
+ description = ('Generates S5 (X)HTML slideshow documents from standalone '
22
+ 'reStructuredText sources. ' + default_description)
23
+
24
+ publish_cmdline(writer_name='s5', description=description)
@@ -0,0 +1,27 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2xetex.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: Guenter Milde
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing Lua/XeLaTeX code.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline
18
+
19
+ description = ('Generates LaTeX documents from standalone reStructuredText '
20
+ 'sources for compilation with the Unicode-aware TeX variants '
21
+ 'XeLaTeX or LuaLaTeX. '
22
+ 'Reads from <source> (default is stdin) and writes to '
23
+ '<destination> (default is stdout). See '
24
+ '<https://docutils.sourceforge.io/docs/user/latex.html> for '
25
+ 'the full reference.')
26
+
27
+ publish_cmdline(writer_name='xetex', description=description)
entorno/bin/rst2xml.py ADDED
@@ -0,0 +1,23 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rst2xml.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing Docutils XML.
9
+ """
10
+
11
+ try:
12
+ import locale
13
+ locale.setlocale(locale.LC_ALL, '')
14
+ except Exception:
15
+ pass
16
+
17
+ from docutils.core import publish_cmdline, default_description
18
+
19
+
20
+ description = ('Generates Docutils-native XML from standalone '
21
+ 'reStructuredText sources. ' + default_description)
22
+
23
+ publish_cmdline(writer_name='xml', description=description)
@@ -0,0 +1,25 @@
1
+ #!/home/linux/Documentos/TSADmetrics/entorno/bin/python
2
+
3
+ # $Id: rstpep2html.py 9115 2022-07-28 17:06:24Z milde $
4
+ # Author: David Goodger <goodger@python.org>
5
+ # Copyright: This module has been placed in the public domain.
6
+
7
+ """
8
+ A minimal front end to the Docutils Publisher, producing HTML from PEP
9
+ (Python Enhancement Proposal) documents.
10
+ """
11
+
12
+ try:
13
+ import locale
14
+ locale.setlocale(locale.LC_ALL, '')
15
+ except Exception:
16
+ pass
17
+
18
+ from docutils.core import publish_cmdline, default_description
19
+
20
+
21
+ description = ('Generates (X)HTML from reStructuredText-format PEP files. '
22
+ + default_description)
23
+
24
+ publish_cmdline(reader_name='pep', writer_name='pep_html',
25
+ description=description)
@@ -0,0 +1,187 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import time
4
+ import os
5
+ from tsadmetrics import *
6
+
7
+ def cargar_prediccion(modelo_nombre):
8
+ """
9
+ Carga las predicciones guardadas previamente.
10
+ """
11
+ nombre_archivo = f'../results/predictions/{modelo_nombre}_pred.csv'
12
+ resultados = pd.read_csv(nombre_archivo)
13
+
14
+ y_true = resultados['ground_truth'].values
15
+ y_pred_binary = resultados['prediction_binary'].values
16
+ y_pred_continuous = resultados['prediction_continuous'].values
17
+ return y_true, y_pred_binary, y_pred_continuous
18
+
19
+ # Lista de modelos y métricas
20
+ nombre_modelos = ['CBLOF', 'IForest', 'KNN', 'LOF','AE1SVM','AutoEncoder','LSTM']
21
+ metrics = [
22
+ ('point_wise_f_score', point_wise_f_score),
23
+ ('point_adjusted_f_score', point_adjusted_f_score),
24
+ ('delay_th_point_adjusted_f_score', delay_th_point_adjusted_f_score),
25
+ ('point_adjusted_at_k_f_score', point_adjusted_at_k_f_score),
26
+ ('latency_sparsity_aw_f_score', latency_sparsity_aw_f_score),
27
+ ('segment_wise_f_score', segment_wise_f_score),
28
+ ('composite_f_score', composite_f_score),
29
+ ('time_tolerant_f_score', time_tolerant_f_score),
30
+ ('range_based_f_score',range_based_f_score),
31
+ ('ts_aware_f_score',ts_aware_f_score),
32
+ ('enhanced_ts_aware_f_score', enhanced_ts_aware_f_score),
33
+ ('affiliation_based_f_score', affiliation_based_f_score),
34
+ ('nab_score', nab_score),
35
+ ('temporal_distance', temporal_distance),
36
+ ('average_detection_count', average_detection_count),
37
+ ('absolute_detection_distance',absolute_detection_distance),
38
+ ('total_detected_in_range',total_detected_in_range),
39
+ ('detection_accuracy_in_range',detection_accuracy_in_range),
40
+ ('weighted_detection_difference',weighted_detection_difference),
41
+ ('binary_pate', binary_pate),
42
+ ('mean_time_to_detect', mean_time_to_detect),
43
+ ]
44
+
45
+ metrics_params = {
46
+ 'delay_th_point_adjusted_f_score': {'k': 10},
47
+ 'point_adjusted_at_k_f_score': {'k': 0.7},
48
+ 'latency_sparsity_aw_f_score': {'ni': 2},
49
+ 'time_tolerant_f_score': {'t': 30},
50
+ 'range_based_f_score': {'p_alpha': 0, 'r_alpha':0},
51
+ 'ts_aware_f_score': {'theta': 0.5, 'alpha':0.5, 'delta': 0, 'beta':1},
52
+ 'enhanced_ts_aware_f_score': {'beta':1,'theta_p': 0.5, 'theta_r':0.1},
53
+ 'total_detected_in_range': {'k': 30},
54
+ 'detection_accuracy_in_range': {'k': 30},
55
+ 'weighted_detection_difference':{'k': 30},
56
+ 'binary_pate': {'early': 20, 'delay': 20}
57
+ }
58
+
59
+ # Crear directorio si no existe
60
+ os.makedirs('../results/computed_metrics', exist_ok=True)
61
+
62
+ # Rutas de los archivos
63
+ results_path = '../results/computed_metrics/resultados.csv'
64
+ times_path = '../results/computed_metrics/tiempos.csv'
65
+
66
+ # Intentar cargar resultados existentes o crear nuevos DataFrames
67
+ try:
68
+ all_results_df = pd.read_csv(results_path)
69
+ all_times_df = pd.read_csv(times_path)
70
+ print("Cargados resultados previos encontrados.")
71
+ except:
72
+ all_results_df = pd.DataFrame(columns=['modelo'] + [m[0] for m in metrics])
73
+ all_times_df = pd.DataFrame(columns=['modelo', 'metrica', 'tiempo'])
74
+ print("No se encontraron resultados previos, comenzando desde cero.")
75
+
76
+ # Función para guardar el progreso
77
+ def guardar_progreso():
78
+ all_results_df.to_csv(results_path, index=False)
79
+ all_times_df.to_csv(times_path, index=False)
80
+ print(f"\nProgreso guardado a las {time.strftime('%H:%M:%S')}")
81
+
82
+ # Tiempo de inicio y última vez que se guardó
83
+ start_time = time.time()
84
+ last_save_time = start_time
85
+
86
+ # Bucle principal de cálculo
87
+ for modelo in nombre_modelos:
88
+ # Verificar si el modelo ya está completo en los resultados
89
+ if modelo in all_results_df['modelo'].values:
90
+ print(f"\nModelo {modelo} ya calculado, saltando...")
91
+ continue
92
+
93
+ print(f"\nComenzando cálculo para modelo: {modelo}")
94
+
95
+ try:
96
+ # Cargar predicciones
97
+ y_true, y_pred, _ = cargar_prediccion(modelo)
98
+
99
+ # Diccionario para almacenar resultados del modelo actual
100
+ model_results = {'modelo': modelo}
101
+ model_times = []
102
+
103
+ for metric_name, metric_func in metrics:
104
+ # Verificar si esta métrica ya está calculada para este modelo
105
+ if not all_results_df.empty and modelo in all_results_df['modelo'].values:
106
+ existing_row = all_results_df[all_results_df['modelo'] == modelo].iloc[0]
107
+ if not pd.isna(existing_row[metric_name]):
108
+ print(f"Métrica {metric_name} ya calculada para {modelo}, saltando...")
109
+ continue
110
+
111
+ print(f"Calculando métrica: {metric_name}, modelo: {modelo}...")
112
+
113
+ try:
114
+ # Calcular métrica y tiempo de ejecución
115
+ start_metric_time = time.time()
116
+
117
+ if metric_name in metrics_params:
118
+ params = metrics_params[metric_name]
119
+ metric_value = metric_func(y_true, y_pred, **params)
120
+ else:
121
+ metric_value = metric_func(y_true, y_pred)
122
+
123
+ computation_time = time.time() - start_metric_time
124
+
125
+ # Actualizar resultados
126
+ model_results[metric_name] = metric_value
127
+ model_times.append({
128
+ 'modelo': modelo,
129
+ 'metrica': metric_name,
130
+ 'tiempo': computation_time
131
+ })
132
+
133
+ print(f"Valor: {metric_value:.4f}, tiempo: {computation_time:.4f}s")
134
+
135
+ # Guardar progreso cada hora
136
+ current_time = time.time()
137
+ if current_time - last_save_time > 3600: # 3600 segundos = 1 hora
138
+ # Añadir resultados parciales
139
+ if modelo not in all_results_df['modelo'].values:
140
+ all_results_df = pd.concat([all_results_df, pd.DataFrame([model_results])], ignore_index=True)
141
+ else:
142
+ idx = all_results_df.index[all_results_df['modelo'] == modelo][0]
143
+ all_results_df.loc[idx, metric_name] = metric_value
144
+
145
+ all_times_df = pd.concat([all_times_df, pd.DataFrame(model_times)], ignore_index=True)
146
+ model_times = [] # Resetear tiempos para no duplicar
147
+
148
+ guardar_progreso()
149
+ last_save_time = current_time
150
+
151
+ except Exception as e:
152
+ print(f"Error calculando {metric_name} para {modelo}: {str(e)}")
153
+ model_results[metric_name] = np.nan
154
+ model_times.append({
155
+ 'modelo': modelo,
156
+ 'metrica': metric_name,
157
+ 'tiempo': np.nan
158
+ })
159
+
160
+ # Añadir resultados completos del modelo a los DataFrames principales
161
+ if modelo not in all_results_df['modelo'].values:
162
+ all_results_df = pd.concat([all_results_df, pd.DataFrame([model_results])], ignore_index=True)
163
+ else:
164
+ # Actualizar fila existente
165
+ idx = all_results_df.index[all_results_df['modelo'] == modelo][0]
166
+ for metric_name in model_results:
167
+ if metric_name != 'modelo':
168
+ all_results_df.loc[idx, metric_name] = model_results[metric_name]
169
+
170
+ all_times_df = pd.concat([all_times_df, pd.DataFrame(model_times)], ignore_index=True)
171
+
172
+ # Guardar después de completar cada modelo
173
+ guardar_progreso()
174
+ last_save_time = time.time()
175
+
176
+ except Exception as e:
177
+ print(f"Error procesando modelo {modelo}: {str(e)}")
178
+ # Añadir filas con NaN para este modelo
179
+ model_results = {'modelo': modelo}
180
+ for m in metrics:
181
+ model_results[m[0]] = np.nan
182
+ all_results_df = pd.concat([all_results_df, pd.DataFrame([model_results])], ignore_index=True)
183
+ guardar_progreso()
184
+
185
+ # Guardar resultados finales
186
+ guardar_progreso()
187
+ print("\nProceso completado. Resultados finales guardados.")
@@ -0,0 +1,109 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import time
4
+ import os
5
+ from tsadmetrics import *
6
+
7
+ # Lista de modelos y métricas
8
+ binary_metrics = [
9
+ ('point_wise_f_score', point_wise_f_score),
10
+ ('point_adjusted_f_score', point_adjusted_f_score),
11
+ ('delay_th_point_adjusted_f_score', delay_th_point_adjusted_f_score),
12
+ ('point_adjusted_at_k_f_score', point_adjusted_at_k_f_score),
13
+ ('latency_sparsity_aw_f_score', latency_sparsity_aw_f_score),
14
+ ('segment_wise_f_score', segment_wise_f_score),
15
+ ('composite_f_score', composite_f_score),
16
+ ('time_tolerant_f_score', time_tolerant_f_score),
17
+ ('range_based_f_score',range_based_f_score),
18
+ ('ts_aware_f_score',ts_aware_f_score),
19
+ ('enhanced_ts_aware_f_score', enhanced_ts_aware_f_score),
20
+ ('affiliation_based_f_score', affiliation_based_f_score),
21
+ ('nab_score', nab_score),
22
+ ('temporal_distance', temporal_distance),
23
+ ('average_detection_count', average_detection_count),
24
+ ('absolute_detection_distance',absolute_detection_distance),
25
+ ('total_detected_in_range',total_detected_in_range),
26
+ ('detection_accuracy_in_range',detection_accuracy_in_range),
27
+ ('weighted_detection_difference',weighted_detection_difference),
28
+ ('binary_pate', binary_pate),
29
+ ('mean_time_to_detect', mean_time_to_detect),
30
+
31
+ ]
32
+ binary_metrics_params ={
33
+ 'delay_th_point_adjusted_f_score': {'k': 10},
34
+ 'point_adjusted_at_k_f_score': {'k': 0.7},
35
+ 'latency_sparsity_aw_f_score': {'ni': 2},
36
+ 'time_tolerant_f_score': {'t': 30},
37
+ 'range_based_f_score': {'p_alpha': 0, 'r_alpha':0}, #Valor por defecto
38
+ 'ts_aware_f_score': {'theta': 0.5, 'alpha':0.5, 'delta': 0, 'beta':1}, #Valor por defecto
39
+ 'enhanced_ts_aware_f_score': {'beta':1,'theta_p': 0.5, 'theta_r':0.1}, #Valor por defecto
40
+ 'total_detected_in_range': {'k': 30},
41
+ 'detection_accuracy_in_range': {'k': 30},
42
+ 'weighted_detection_difference':{'k': 3},
43
+ 'binary_pate': {'early': 20, 'delay': 20}
44
+
45
+ }
46
+
47
+ continuous_metrics = [
48
+ ('precision_at_k', precision_at_k),
49
+ ('auc_roc_pw', auc_roc_pw),
50
+ ('auc_pr_pw', auc_pr_pw),
51
+ ('auc_pr_pa', auc_pr_pa),
52
+ ('auc_pr_sw', auc_pr_sw),
53
+ ('vus_roc', vus_roc),
54
+ ('vus_pr', vus_pr),
55
+ ('real_pate', real_pate)]
56
+
57
+ continuous_metrics_params ={
58
+ 'vus_roc': {'window': 4},
59
+ 'vus_pr': {'window': 4},
60
+ 'real_pate': {'early': 3, 'delay': 3},
61
+
62
+ }
63
+ SIZE = 1000
64
+ # Cargar predicciones
65
+ y_true, y_pred = np.random.choice([0, 1], size=SIZE), np.random.choice([0, 1], size=SIZE)
66
+
67
+ Binary_mode = 1
68
+
69
+ if Binary_mode == 0:
70
+ for metric_name, metric_func in binary_metrics:
71
+
72
+ # Calcular métrica y tiempo de ejecución
73
+
74
+
75
+ start_time = time.time()
76
+ if metric_name in binary_metrics_params:
77
+ params = binary_metrics_params[metric_name]
78
+ metric_value = metric_func(y_true, y_pred, **params)
79
+ else:
80
+ metric_value = metric_func(y_true, y_pred)
81
+ computation_time = time.time() - start_time
82
+
83
+
84
+
85
+ print(f"Métrica: {metric_name} - Valor: {metric_value:.4f} - Tiempo: {computation_time:.4f}s")
86
+
87
+ else:
88
+ y_true = np.random.choice([0, 1], size=SIZE)
89
+ y_pred = np.random.rand(SIZE) # Predicciones continuas
90
+
91
+ # Calcular métrica y tiempo de ejecución
92
+
93
+ for metric_name, metric_func in continuous_metrics:
94
+
95
+ start_time = time.time()
96
+ if metric_name in continuous_metrics_params:
97
+ params = continuous_metrics_params[metric_name]
98
+ metric_value = metric_func(y_true, y_pred, **params)
99
+ else:
100
+ metric_value = metric_func(y_true, y_pred)
101
+ computation_time = time.time() - start_time
102
+
103
+
104
+
105
+ print(f"Métrica: {metric_name} - Valor: {metric_value:.4f} - Tiempo: {computation_time:.4f}s")
106
+
107
+
108
+
109
+