body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
06dfd3af7e5771ab5f267fc54dc6fe57eaa817049131a2d09c64e492546ae949 | @property
def interactive(self):
'\n bool: interactive mode (display figures) or not\n\n Note:\n When running scripts, interactive mode cannot be selected.\n '
return self._interactive | bool: interactive mode (display figures) or not
Note:
When running scripts, interactive mode cannot be selected. | covsirphy/analysis/scenario.py | interactive | fadelrahman31/modified-covsirphhy | 0 | python | @property
def interactive(self):
'\n bool: interactive mode (display figures) or not\n\n Note:\n When running scripts, interactive mode cannot be selected.\n '
return self._interactive | @property
def interactive(self):
'\n bool: interactive mode (display figures) or not\n\n Note:\n When running scripts, interactive mode cannot be selected.\n '
return self._interactive<|docstring|>bool: interactive mode (display figures) or not
Note:
When running scripts, interactive mode cannot be selected.<|endoftext|> |
6ca95ddaaabb4bf203efc923b66895ab8600cf78a16a6350fa9d65dd5b294d16 | def register(self, jhu_data=None, population_data=None, extras=None):
'\n Register datasets.\n\n Args:\n jhu_data (covsirphy.JHUData or None): object of records\n population_data (covsirphy.PopulationData or None): PopulationData object\n extras (list[covsirphy.CleaningBase] or None): extra datasets\n\n Raises:\n TypeError: non-data cleaning instance was included\n UnExpectedValueError: instance of un-expected data cleaning class was included as an extra dataset\n '
self._data.register(jhu_data=jhu_data, population_data=population_data, extras=extras)
if (self._data.main_satisfied and (not self._tracker_dict)):
self.timepoints() | Register datasets.
Args:
jhu_data (covsirphy.JHUData or None): object of records
population_data (covsirphy.PopulationData or None): PopulationData object
extras (list[covsirphy.CleaningBase] or None): extra datasets
Raises:
TypeError: non-data cleaning instance was included
UnExpectedValueError: instance of un-expected data cleaning class was included as an extra dataset | covsirphy/analysis/scenario.py | register | fadelrahman31/modified-covsirphhy | 0 | python | def register(self, jhu_data=None, population_data=None, extras=None):
'\n Register datasets.\n\n Args:\n jhu_data (covsirphy.JHUData or None): object of records\n population_data (covsirphy.PopulationData or None): PopulationData object\n extras (list[covsirphy.CleaningBase] or None): extra datasets\n\n Raises:\n TypeError: non-data cleaning instance was included\n UnExpectedValueError: instance of un-expected data cleaning class was included as an extra dataset\n '
self._data.register(jhu_data=jhu_data, population_data=population_data, extras=extras)
if (self._data.main_satisfied and (not self._tracker_dict)):
self.timepoints() | def register(self, jhu_data=None, population_data=None, extras=None):
'\n Register datasets.\n\n Args:\n jhu_data (covsirphy.JHUData or None): object of records\n population_data (covsirphy.PopulationData or None): PopulationData object\n extras (list[covsirphy.CleaningBase] or None): extra datasets\n\n Raises:\n TypeError: non-data cleaning instance was included\n UnExpectedValueError: instance of un-expected data cleaning class was included as an extra dataset\n '
self._data.register(jhu_data=jhu_data, population_data=population_data, extras=extras)
if (self._data.main_satisfied and (not self._tracker_dict)):
self.timepoints()<|docstring|>Register datasets.
Args:
jhu_data (covsirphy.JHUData or None): object of records
population_data (covsirphy.PopulationData or None): PopulationData object
extras (list[covsirphy.CleaningBase] or None): extra datasets
Raises:
TypeError: non-data cleaning instance was included
UnExpectedValueError: instance of un-expected data cleaning class was included as an extra dataset<|endoftext|> |
7af15a7e81e04bc3ee00acc64b8568e069a5f68b8817d6eaa6defc5b5d8c7e7b | def timepoints(self, first_date=None, last_date=None, today=None):
'\n Set the range of data and reference date to determine past/future of phases.\n\n Args:\n first_date (str or None): the first date of the records or None (min date of main dataset)\n last_date (str or None): the first date of the records or None (max date of main dataset)\n today (str or None): reference date to determine whether a phase is a past phase or a future phase\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n\n Note:\n When @today is None, the reference date will be the same as @last_date (or max date).\n '
self._data.timepoints(first_date=first_date, last_date=last_date, today=today)
self._init_trackers() | Set the range of data and reference date to determine past/future of phases.
Args:
first_date (str or None): the first date of the records or None (min date of main dataset)
last_date (str or None): the first date of the records or None (max date of main dataset)
today (str or None): reference date to determine whether a phase is a past phase or a future phase
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
Note:
When @today is None, the reference date will be the same as @last_date (or max date). | covsirphy/analysis/scenario.py | timepoints | fadelrahman31/modified-covsirphhy | 0 | python | def timepoints(self, first_date=None, last_date=None, today=None):
'\n Set the range of data and reference date to determine past/future of phases.\n\n Args:\n first_date (str or None): the first date of the records or None (min date of main dataset)\n last_date (str or None): the first date of the records or None (max date of main dataset)\n today (str or None): reference date to determine whether a phase is a past phase or a future phase\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n\n Note:\n When @today is None, the reference date will be the same as @last_date (or max date).\n '
self._data.timepoints(first_date=first_date, last_date=last_date, today=today)
self._init_trackers() | def timepoints(self, first_date=None, last_date=None, today=None):
'\n Set the range of data and reference date to determine past/future of phases.\n\n Args:\n first_date (str or None): the first date of the records or None (min date of main dataset)\n last_date (str or None): the first date of the records or None (max date of main dataset)\n today (str or None): reference date to determine whether a phase is a past phase or a future phase\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n\n Note:\n When @today is None, the reference date will be the same as @last_date (or max date).\n '
self._data.timepoints(first_date=first_date, last_date=last_date, today=today)
self._init_trackers()<|docstring|>Set the range of data and reference date to determine past/future of phases.
Args:
first_date (str or None): the first date of the records or None (min date of main dataset)
last_date (str or None): the first date of the records or None (max date of main dataset)
today (str or None): reference date to determine whether a phase is a past phase or a future phase
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
Note:
When @today is None, the reference date will be the same as @last_date (or max date).<|endoftext|> |
5ae95a70af2133fac5f72a62d3eaa1700cec1e09e18ad80d58cbfd6d04b3079f | def line_plot(self, df, show_figure=True, filename=None, **kwargs):
'\n Display or save a line plot of the dataframe.\n\n Args:\n show_figure (bool): whether show figure when interactive mode or not\n filename (str or None): filename of the figure or None (not save) when script mode\n\n Note:\n When interactive mode and @show_figure is True, display the figure.\n When script mode and filename is not None, save the figure.\n When using interactive shell, we can change the modes by Scenario.interactive = True/False.\n '
if (self._interactive and show_figure):
return line_plot(df=df, filename=None, **kwargs)
if ((not self._interactive) and (filename is not None)):
return line_plot(df=df, filename=filename, **kwargs) | Display or save a line plot of the dataframe.
Args:
show_figure (bool): whether show figure when interactive mode or not
filename (str or None): filename of the figure or None (not save) when script mode
Note:
When interactive mode and @show_figure is True, display the figure.
When script mode and filename is not None, save the figure.
When using interactive shell, we can change the modes by Scenario.interactive = True/False. | covsirphy/analysis/scenario.py | line_plot | fadelrahman31/modified-covsirphhy | 0 | python | def line_plot(self, df, show_figure=True, filename=None, **kwargs):
'\n Display or save a line plot of the dataframe.\n\n Args:\n show_figure (bool): whether show figure when interactive mode or not\n filename (str or None): filename of the figure or None (not save) when script mode\n\n Note:\n When interactive mode and @show_figure is True, display the figure.\n When script mode and filename is not None, save the figure.\n When using interactive shell, we can change the modes by Scenario.interactive = True/False.\n '
if (self._interactive and show_figure):
return line_plot(df=df, filename=None, **kwargs)
if ((not self._interactive) and (filename is not None)):
return line_plot(df=df, filename=filename, **kwargs) | def line_plot(self, df, show_figure=True, filename=None, **kwargs):
'\n Display or save a line plot of the dataframe.\n\n Args:\n show_figure (bool): whether show figure when interactive mode or not\n filename (str or None): filename of the figure or None (not save) when script mode\n\n Note:\n When interactive mode and @show_figure is True, display the figure.\n When script mode and filename is not None, save the figure.\n When using interactive shell, we can change the modes by Scenario.interactive = True/False.\n '
if (self._interactive and show_figure):
return line_plot(df=df, filename=None, **kwargs)
if ((not self._interactive) and (filename is not None)):
return line_plot(df=df, filename=filename, **kwargs)<|docstring|>Display or save a line plot of the dataframe.
Args:
show_figure (bool): whether show figure when interactive mode or not
filename (str or None): filename of the figure or None (not save) when script mode
Note:
When interactive mode and @show_figure is True, display the figure.
When script mode and filename is not None, save the figure.
When using interactive shell, we can change the modes by Scenario.interactive = True/False.<|endoftext|> |
d907806c49d45e0aef7eb849b0322e845f4034188939e86cc78488a3cc2af3dc | def complement(self, **kwargs):
'\n Complement the number of recovered cases, if necessary.\n\n Args:\n kwargs: the other arguments of JHUData.subset_complement()\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=True, **kwargs)
return self | Complement the number of recovered cases, if necessary.
Args:
kwargs: the other arguments of JHUData.subset_complement()
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | complement | fadelrahman31/modified-covsirphhy | 0 | python | def complement(self, **kwargs):
'\n Complement the number of recovered cases, if necessary.\n\n Args:\n kwargs: the other arguments of JHUData.subset_complement()\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=True, **kwargs)
return self | def complement(self, **kwargs):
'\n Complement the number of recovered cases, if necessary.\n\n Args:\n kwargs: the other arguments of JHUData.subset_complement()\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=True, **kwargs)
return self<|docstring|>Complement the number of recovered cases, if necessary.
Args:
kwargs: the other arguments of JHUData.subset_complement()
Returns:
covsirphy.Scenario: self<|endoftext|> |
f046cbc506df064daf31c4d3320e68fdb5aa72ef816cd2c80b8f3943e10d0819 | def complement_reverse(self):
'\n Restore the raw records. Reverse method of covsirphy.Scenario.complement().\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=False)
return self | Restore the raw records. Reverse method of covsirphy.Scenario.complement().
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | complement_reverse | fadelrahman31/modified-covsirphhy | 0 | python | def complement_reverse(self):
'\n Restore the raw records. Reverse method of covsirphy.Scenario.complement().\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=False)
return self | def complement_reverse(self):
'\n Restore the raw records. Reverse method of covsirphy.Scenario.complement().\n\n Returns:\n covsirphy.Scenario: self\n '
self._data.switch_complement(whether=False)
return self<|docstring|>Restore the raw records. Reverse method of covsirphy.Scenario.complement().
Returns:
covsirphy.Scenario: self<|endoftext|> |
549c9049ac866bd495543e8d29c0d95aaec42efe64d7906e502bb225899f4926 | def show_complement(self, **kwargs):
'\n Show the details of complement that was (or will be) performed for the records.\n\n Args:\n kwargs: keyword arguments of JHUDataComplementHandler() i.e. control factors of complement\n\n Returns:\n pandas.DataFrame: as the same as JHUData.show_complement()\n '
self._data.switch_complement(whether=None, **kwargs)
return self._data.show_complement() | Show the details of complement that was (or will be) performed for the records.
Args:
kwargs: keyword arguments of JHUDataComplementHandler() i.e. control factors of complement
Returns:
pandas.DataFrame: as the same as JHUData.show_complement() | covsirphy/analysis/scenario.py | show_complement | fadelrahman31/modified-covsirphhy | 0 | python | def show_complement(self, **kwargs):
'\n Show the details of complement that was (or will be) performed for the records.\n\n Args:\n kwargs: keyword arguments of JHUDataComplementHandler() i.e. control factors of complement\n\n Returns:\n pandas.DataFrame: as the same as JHUData.show_complement()\n '
self._data.switch_complement(whether=None, **kwargs)
return self._data.show_complement() | def show_complement(self, **kwargs):
'\n Show the details of complement that was (or will be) performed for the records.\n\n Args:\n kwargs: keyword arguments of JHUDataComplementHandler() i.e. control factors of complement\n\n Returns:\n pandas.DataFrame: as the same as JHUData.show_complement()\n '
self._data.switch_complement(whether=None, **kwargs)
return self._data.show_complement()<|docstring|>Show the details of complement that was (or will be) performed for the records.
Args:
kwargs: keyword arguments of JHUDataComplementHandler() i.e. control factors of complement
Returns:
pandas.DataFrame: as the same as JHUData.show_complement()<|endoftext|> |
c866d5bd017027085e24efbc44fee3c978b07f57d793d030c039900eed6b66b7 | def _convert_variables(self, abbr, candidates):
'\n Convert abbreviated variable names to complete names.\n\n Args:\n abbr (list[str] or str or None): variable names or abbreviated names\n candidates (list[str]): all candidates\n\n Returns:\n list[str]: complete names of variables\n\n Note:\n Selectable values of @abbr are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
if (abbr is None):
return [self.CI, self.F, self.R]
if (abbr == 'all'):
return self._ensure_list(candidates, name='candidates')
abbr_dict = {'C': self.C, 'I': self.CI, 'F': self.F, 'R': self.R}
variables = (list(abbr) if isinstance(abbr, str) else abbr)
variables = [abbr_dict.get(v, v) for v in variables]
return self._ensure_list(variables, candidates=candidates, name='variables') | Convert abbreviated variable names to complete names.
Args:
abbr (list[str] or str or None): variable names or abbreviated names
candidates (list[str]): all candidates
Returns:
list[str]: complete names of variables
Note:
Selectable values of @abbr are as follows.
- None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)
- list[str]: return the selected variables
- "all": the all available variables
- str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC" | covsirphy/analysis/scenario.py | _convert_variables | fadelrahman31/modified-covsirphhy | 0 | python | def _convert_variables(self, abbr, candidates):
'\n Convert abbreviated variable names to complete names.\n\n Args:\n abbr (list[str] or str or None): variable names or abbreviated names\n candidates (list[str]): all candidates\n\n Returns:\n list[str]: complete names of variables\n\n Note:\n Selectable values of @abbr are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
if (abbr is None):
return [self.CI, self.F, self.R]
if (abbr == 'all'):
return self._ensure_list(candidates, name='candidates')
abbr_dict = {'C': self.C, 'I': self.CI, 'F': self.F, 'R': self.R}
variables = (list(abbr) if isinstance(abbr, str) else abbr)
variables = [abbr_dict.get(v, v) for v in variables]
return self._ensure_list(variables, candidates=candidates, name='variables') | def _convert_variables(self, abbr, candidates):
'\n Convert abbreviated variable names to complete names.\n\n Args:\n abbr (list[str] or str or None): variable names or abbreviated names\n candidates (list[str]): all candidates\n\n Returns:\n list[str]: complete names of variables\n\n Note:\n Selectable values of @abbr are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
if (abbr is None):
return [self.CI, self.F, self.R]
if (abbr == 'all'):
return self._ensure_list(candidates, name='candidates')
abbr_dict = {'C': self.C, 'I': self.CI, 'F': self.F, 'R': self.R}
variables = (list(abbr) if isinstance(abbr, str) else abbr)
variables = [abbr_dict.get(v, v) for v in variables]
return self._ensure_list(variables, candidates=candidates, name='variables')<|docstring|>Convert abbreviated variable names to complete names.
Args:
abbr (list[str] or str or None): variable names or abbreviated names
candidates (list[str]): all candidates
Returns:
list[str]: complete names of variables
Note:
Selectable values of @abbr are as follows.
- None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)
- list[str]: return the selected variables
- "all": the all available variables
- str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"<|endoftext|> |
cdb4a0168a6ba7406d49f3b161af77036b1574884d041938be3a64379693d8d6 | def records(self, variables=None, **kwargs):
'\n Return the records as a dataframe.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n NotRegisteredExtraError: some variables are not included in the main datasets\n and no extra datasets were registered\n\n Returns:\n pandas.DataFrame\n\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Columns set by @variables (int)\n\n Note:\n - Records with Recovered > 0 will be selected.\n - If complement was performed by Scenario.complement() or Scenario(auto_complement=True),\n The kind of complement will be added to the title of the figure.\n\n Note:\n Selectable values of @variables are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
all_df = self._data.records_all().set_index(self.DATE)
variables = self._convert_variables(variables, all_df.columns.tolist())
df = all_df.loc[(:, variables)]
if self._data.complemented:
title = f'''{self.area}: Cases over time
with {self._data.complemented}'''
else:
title = f'{self.area}: Cases over time'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df.reset_index() | Return the records as a dataframe.
Args:
variables (list[str] or str or None): variable names or abbreviated names
kwargs: the other keyword arguments of Scenario.line_plot()
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
NotRegisteredExtraError: some variables are not included in the main datasets
and no extra datasets were registered
Returns:
pandas.DataFrame
Index
reset index
Columns
- Date (pd.Timestamp): Observation date
- Columns set by @variables (int)
Note:
- Records with Recovered > 0 will be selected.
- If complement was performed by Scenario.complement() or Scenario(auto_complement=True),
The kind of complement will be added to the title of the figure.
Note:
Selectable values of @variables are as follows.
- None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)
- list[str]: return the selected variables
- "all": the all available variables
- str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC" | covsirphy/analysis/scenario.py | records | fadelrahman31/modified-covsirphhy | 0 | python | def records(self, variables=None, **kwargs):
'\n Return the records as a dataframe.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n NotRegisteredExtraError: some variables are not included in the main datasets\n and no extra datasets were registered\n\n Returns:\n pandas.DataFrame\n\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Columns set by @variables (int)\n\n Note:\n - Records with Recovered > 0 will be selected.\n - If complement was performed by Scenario.complement() or Scenario(auto_complement=True),\n The kind of complement will be added to the title of the figure.\n\n Note:\n Selectable values of @variables are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
all_df = self._data.records_all().set_index(self.DATE)
variables = self._convert_variables(variables, all_df.columns.tolist())
df = all_df.loc[(:, variables)]
if self._data.complemented:
title = f'{self.area}: Cases over time
with {self._data.complemented}'
else:
title = f'{self.area}: Cases over time'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df.reset_index() | def records(self, variables=None, **kwargs):
'\n Return the records as a dataframe.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n NotRegisteredExtraError: some variables are not included in the main datasets\n and no extra datasets were registered\n\n Returns:\n pandas.DataFrame\n\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Columns set by @variables (int)\n\n Note:\n - Records with Recovered > 0 will be selected.\n - If complement was performed by Scenario.complement() or Scenario(auto_complement=True),\n The kind of complement will be added to the title of the figure.\n\n Note:\n Selectable values of @variables are as follows.\n - None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)\n - list[str]: return the selected variables\n - "all": the all available variables\n - str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"\n '
all_df = self._data.records_all().set_index(self.DATE)
variables = self._convert_variables(variables, all_df.columns.tolist())
df = all_df.loc[(:, variables)]
if self._data.complemented:
title = f'{self.area}: Cases over time
with {self._data.complemented}'
else:
title = f'{self.area}: Cases over time'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df.reset_index()<|docstring|>Return the records as a dataframe.
Args:
variables (list[str] or str or None): variable names or abbreviated names
kwargs: the other keyword arguments of Scenario.line_plot()
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
NotRegisteredExtraError: some variables are not included in the main datasets
and no extra datasets were registered
Returns:
pandas.DataFrame
Index
reset index
Columns
- Date (pd.Timestamp): Observation date
- Columns set by @variables (int)
Note:
- Records with Recovered > 0 will be selected.
- If complement was performed by Scenario.complement() or Scenario(auto_complement=True),
The kind of complement will be added to the title of the figure.
Note:
Selectable values of @variables are as follows.
- None: return default list, ["Infected", "Recovered", "Fatal"] (changed in the future)
- list[str]: return the selected variables
- "all": the all available variables
- str: abbr, like "CIFR" (Confirmed/Infected/Fatal/Recovered), "CFR", "RC"<|endoftext|> |
e614ff23622d3f40b9a4351ca1caeda6794fa654893a04b0a1d4800df815b084 | def records_diff(self, variables=None, window=7, **kwargs):
'\n Return the number of daily new cases (the first discreate difference of records).\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n window (int): window of moving average, >= 1\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n - Date (pd.Timestamp): Observation date\n Columns\n - Confirmed (int): daily new cases of Confirmed, if calculated\n - Infected (int): daily new cases of Infected, if calculated\n - Fatal (int): daily new cases of Fatal, if calculated\n - Recovered (int): daily new cases of Recovered, if calculated\n '
window = self._ensure_natural_int(window, name='window')
df = self.records(variables=variables, show_figure=False).set_index(self.DATE)
df = df.diff().dropna()
df = df.rolling(window=window).mean().dropna().astype(np.int64)
if self._data.complemented:
title = f'''{self.area}: Daily new cases
with {self._data.complemented}'''
else:
title = f'{self.area}: Daily new cases'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df | Return the number of daily new cases (the first discreate difference of records).
Args:
variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())
window (int): window of moving average, >= 1
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame
Index
- Date (pd.Timestamp): Observation date
Columns
- Confirmed (int): daily new cases of Confirmed, if calculated
- Infected (int): daily new cases of Infected, if calculated
- Fatal (int): daily new cases of Fatal, if calculated
- Recovered (int): daily new cases of Recovered, if calculated | covsirphy/analysis/scenario.py | records_diff | fadelrahman31/modified-covsirphhy | 0 | python | def records_diff(self, variables=None, window=7, **kwargs):
'\n Return the number of daily new cases (the first discreate difference of records).\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n window (int): window of moving average, >= 1\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n - Date (pd.Timestamp): Observation date\n Columns\n - Confirmed (int): daily new cases of Confirmed, if calculated\n - Infected (int): daily new cases of Infected, if calculated\n - Fatal (int): daily new cases of Fatal, if calculated\n - Recovered (int): daily new cases of Recovered, if calculated\n '
window = self._ensure_natural_int(window, name='window')
df = self.records(variables=variables, show_figure=False).set_index(self.DATE)
df = df.diff().dropna()
df = df.rolling(window=window).mean().dropna().astype(np.int64)
if self._data.complemented:
title = f'{self.area}: Daily new cases
with {self._data.complemented}'
else:
title = f'{self.area}: Daily new cases'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df | def records_diff(self, variables=None, window=7, **kwargs):
'\n Return the number of daily new cases (the first discreate difference of records).\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n window (int): window of moving average, >= 1\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n - Date (pd.Timestamp): Observation date\n Columns\n - Confirmed (int): daily new cases of Confirmed, if calculated\n - Infected (int): daily new cases of Infected, if calculated\n - Fatal (int): daily new cases of Fatal, if calculated\n - Recovered (int): daily new cases of Recovered, if calculated\n '
window = self._ensure_natural_int(window, name='window')
df = self.records(variables=variables, show_figure=False).set_index(self.DATE)
df = df.diff().dropna()
df = df.rolling(window=window).mean().dropna().astype(np.int64)
if self._data.complemented:
title = f'{self.area}: Daily new cases
with {self._data.complemented}'
else:
title = f'{self.area}: Daily new cases'
self.line_plot(df=df, title=title, y_integer=True, **kwargs)
return df<|docstring|>Return the number of daily new cases (the first discreate difference of records).
Args:
variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())
window (int): window of moving average, >= 1
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame
Index
- Date (pd.Timestamp): Observation date
Columns
- Confirmed (int): daily new cases of Confirmed, if calculated
- Infected (int): daily new cases of Infected, if calculated
- Fatal (int): daily new cases of Fatal, if calculated
- Recovered (int): daily new cases of Recovered, if calculated<|endoftext|> |
1e244ea34c402622ece32351512302883e8582f08641a8d67d134863d1da6a05 | def _init_trackers(self):
'\n Initialize dictionary of trackers.\n '
data = copy.deepcopy(self._data)
series = ParamTracker.create_series(first_date=data.first_date, last_date=data.today, population=data.population)
tracker = ParamTracker(record_df=self._data.records(extras=False), phase_series=series, area=self.area, tau=self.tau)
self._tracker_dict = {self.MAIN: tracker} | Initialize dictionary of trackers. | covsirphy/analysis/scenario.py | _init_trackers | fadelrahman31/modified-covsirphhy | 0 | python | def _init_trackers(self):
'\n \n '
data = copy.deepcopy(self._data)
series = ParamTracker.create_series(first_date=data.first_date, last_date=data.today, population=data.population)
tracker = ParamTracker(record_df=self._data.records(extras=False), phase_series=series, area=self.area, tau=self.tau)
self._tracker_dict = {self.MAIN: tracker} | def _init_trackers(self):
'\n \n '
data = copy.deepcopy(self._data)
series = ParamTracker.create_series(first_date=data.first_date, last_date=data.today, population=data.population)
tracker = ParamTracker(record_df=self._data.records(extras=False), phase_series=series, area=self.area, tau=self.tau)
self._tracker_dict = {self.MAIN: tracker}<|docstring|>Initialize dictionary of trackers.<|endoftext|> |
ff9a381475519cd6ba8a31682f0bd7b8fe9e7d0c3fbd6c27d087f557d0ad40fb | def _tracker(self, name, template='Main'):
'\n Ensure that the phases series is registered.\n If not registered, copy the template phase series.\n\n Args:\n name (str): phase series name\n template (str): name of template phase series\n\n Returns:\n covsirphy.ParamTracker\n '
if (name in self._tracker_dict):
return self._tracker_dict[name]
if (template not in self._tracker_dict):
raise ScenarioNotFoundError(template)
tracker = copy.deepcopy(self._tracker_dict[template])
self._tracker_dict[name] = tracker
return tracker | Ensure that the phases series is registered.
If not registered, copy the template phase series.
Args:
name (str): phase series name
template (str): name of template phase series
Returns:
covsirphy.ParamTracker | covsirphy/analysis/scenario.py | _tracker | fadelrahman31/modified-covsirphhy | 0 | python | def _tracker(self, name, template='Main'):
'\n Ensure that the phases series is registered.\n If not registered, copy the template phase series.\n\n Args:\n name (str): phase series name\n template (str): name of template phase series\n\n Returns:\n covsirphy.ParamTracker\n '
if (name in self._tracker_dict):
return self._tracker_dict[name]
if (template not in self._tracker_dict):
raise ScenarioNotFoundError(template)
tracker = copy.deepcopy(self._tracker_dict[template])
self._tracker_dict[name] = tracker
return tracker | def _tracker(self, name, template='Main'):
'\n Ensure that the phases series is registered.\n If not registered, copy the template phase series.\n\n Args:\n name (str): phase series name\n template (str): name of template phase series\n\n Returns:\n covsirphy.ParamTracker\n '
if (name in self._tracker_dict):
return self._tracker_dict[name]
if (template not in self._tracker_dict):
raise ScenarioNotFoundError(template)
tracker = copy.deepcopy(self._tracker_dict[template])
self._tracker_dict[name] = tracker
return tracker<|docstring|>Ensure that the phases series is registered.
If not registered, copy the template phase series.
Args:
name (str): phase series name
template (str): name of template phase series
Returns:
covsirphy.ParamTracker<|endoftext|> |
67946b36c99ca57ed462ae28b5041e7edd4a81f87aba9193ae3419832cfcabf2 | def add(self, name='Main', end_date=None, days=None, population=None, model=None, **kwargs):
"\n Add a new phase.\n The start date will be the next date of the last registered phase.\n\n Args:\n name (str): phase series name, 'Main' or user-defined name\n end_date (str): end date of the new phase\n days (int): the number of days to add\n population (int or None): population value of the start date\n model (covsirphy.ModelBase or None): ODE model\n kwargs: keyword arguments of ODE model parameters, not including tau value.\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n - If the phases series has not been registered, new phase series will be created.\n - Either @end_date or @days must be specified.\n - If @end_date and @days are None, the end date will be the last date of the records.\n - If both of @end_date and @days were specified, @end_date will be used.\n - If @popultion is None, initial value will be used.\n - If @model is None, the model of the last phase will be used.\n - Tau will be fixed as the last phase's value.\n - kwargs: Default values are the parameter values of the last phase.\n "
if (end_date is not None):
self._ensure_date(end_date, name='end_date')
tracker = self._tracker(name)
try:
tracker.add(end_date=end_date, days=days, population=population, model=model, **kwargs)
except ValueError:
last_date = tracker.last_end_date()
raise ValueError(f'@end_date must be over {last_date}. However, {end_date} was applied.') from None
self._tracker_dict[name] = tracker
return self | Add a new phase.
The start date will be the next date of the last registered phase.
Args:
name (str): phase series name, 'Main' or user-defined name
end_date (str): end date of the new phase
days (int): the number of days to add
population (int or None): population value of the start date
model (covsirphy.ModelBase or None): ODE model
kwargs: keyword arguments of ODE model parameters, not including tau value.
Returns:
covsirphy.Scenario: self
Note:
- If the phases series has not been registered, new phase series will be created.
- Either @end_date or @days must be specified.
- If @end_date and @days are None, the end date will be the last date of the records.
- If both of @end_date and @days were specified, @end_date will be used.
- If @popultion is None, initial value will be used.
- If @model is None, the model of the last phase will be used.
- Tau will be fixed as the last phase's value.
- kwargs: Default values are the parameter values of the last phase. | covsirphy/analysis/scenario.py | add | fadelrahman31/modified-covsirphhy | 0 | python | def add(self, name='Main', end_date=None, days=None, population=None, model=None, **kwargs):
"\n Add a new phase.\n The start date will be the next date of the last registered phase.\n\n Args:\n name (str): phase series name, 'Main' or user-defined name\n end_date (str): end date of the new phase\n days (int): the number of days to add\n population (int or None): population value of the start date\n model (covsirphy.ModelBase or None): ODE model\n kwargs: keyword arguments of ODE model parameters, not including tau value.\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n - If the phases series has not been registered, new phase series will be created.\n - Either @end_date or @days must be specified.\n - If @end_date and @days are None, the end date will be the last date of the records.\n - If both of @end_date and @days were specified, @end_date will be used.\n - If @popultion is None, initial value will be used.\n - If @model is None, the model of the last phase will be used.\n - Tau will be fixed as the last phase's value.\n - kwargs: Default values are the parameter values of the last phase.\n "
if (end_date is not None):
self._ensure_date(end_date, name='end_date')
tracker = self._tracker(name)
try:
tracker.add(end_date=end_date, days=days, population=population, model=model, **kwargs)
except ValueError:
last_date = tracker.last_end_date()
raise ValueError(f'@end_date must be over {last_date}. However, {end_date} was applied.') from None
self._tracker_dict[name] = tracker
return self | def add(self, name='Main', end_date=None, days=None, population=None, model=None, **kwargs):
"\n Add a new phase.\n The start date will be the next date of the last registered phase.\n\n Args:\n name (str): phase series name, 'Main' or user-defined name\n end_date (str): end date of the new phase\n days (int): the number of days to add\n population (int or None): population value of the start date\n model (covsirphy.ModelBase or None): ODE model\n kwargs: keyword arguments of ODE model parameters, not including tau value.\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n - If the phases series has not been registered, new phase series will be created.\n - Either @end_date or @days must be specified.\n - If @end_date and @days are None, the end date will be the last date of the records.\n - If both of @end_date and @days were specified, @end_date will be used.\n - If @popultion is None, initial value will be used.\n - If @model is None, the model of the last phase will be used.\n - Tau will be fixed as the last phase's value.\n - kwargs: Default values are the parameter values of the last phase.\n "
if (end_date is not None):
self._ensure_date(end_date, name='end_date')
tracker = self._tracker(name)
try:
tracker.add(end_date=end_date, days=days, population=population, model=model, **kwargs)
except ValueError:
last_date = tracker.last_end_date()
raise ValueError(f'@end_date must be over {last_date}. However, {end_date} was applied.') from None
self._tracker_dict[name] = tracker
return self<|docstring|>Add a new phase.
The start date will be the next date of the last registered phase.
Args:
name (str): phase series name, 'Main' or user-defined name
end_date (str): end date of the new phase
days (int): the number of days to add
population (int or None): population value of the start date
model (covsirphy.ModelBase or None): ODE model
kwargs: keyword arguments of ODE model parameters, not including tau value.
Returns:
covsirphy.Scenario: self
Note:
- If the phases series has not been registered, new phase series will be created.
- Either @end_date or @days must be specified.
- If @end_date and @days are None, the end date will be the last date of the records.
- If both of @end_date and @days were specified, @end_date will be used.
- If @popultion is None, initial value will be used.
- If @model is None, the model of the last phase will be used.
- Tau will be fixed as the last phase's value.
- kwargs: Default values are the parameter values of the last phase.<|endoftext|> |
38a1052090d0c10dc4a7225647d70d2d1edf2fc09a7b8d56321a8d787e99f356 | def clear(self, name='Main', include_past=False, template='Main'):
'\n Clear phase information.\n\n Args:\n name (str): scenario name\n include_past (bool): if True, past phases will be removed as well as future phases\n template (str): name of template scenario\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If un-registered scenario name was specified, new scenario will be created.\n Future phases will be always deleted.\n '
tracker = self._tracker(name, template=template)
if include_past:
self[name] = tracker.delete_all()
else:
self[name] = tracker.delete(phases=tracker.future_phases()[0])
return self | Clear phase information.
Args:
name (str): scenario name
include_past (bool): if True, past phases will be removed as well as future phases
template (str): name of template scenario
Returns:
covsirphy.Scenario: self
Note:
If un-registered scenario name was specified, new scenario will be created.
Future phases will be always deleted. | covsirphy/analysis/scenario.py | clear | fadelrahman31/modified-covsirphhy | 0 | python | def clear(self, name='Main', include_past=False, template='Main'):
'\n Clear phase information.\n\n Args:\n name (str): scenario name\n include_past (bool): if True, past phases will be removed as well as future phases\n template (str): name of template scenario\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If un-registered scenario name was specified, new scenario will be created.\n Future phases will be always deleted.\n '
tracker = self._tracker(name, template=template)
if include_past:
self[name] = tracker.delete_all()
else:
self[name] = tracker.delete(phases=tracker.future_phases()[0])
return self | def clear(self, name='Main', include_past=False, template='Main'):
'\n Clear phase information.\n\n Args:\n name (str): scenario name\n include_past (bool): if True, past phases will be removed as well as future phases\n template (str): name of template scenario\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If un-registered scenario name was specified, new scenario will be created.\n Future phases will be always deleted.\n '
tracker = self._tracker(name, template=template)
if include_past:
self[name] = tracker.delete_all()
else:
self[name] = tracker.delete(phases=tracker.future_phases()[0])
return self<|docstring|>Clear phase information.
Args:
name (str): scenario name
include_past (bool): if True, past phases will be removed as well as future phases
template (str): name of template scenario
Returns:
covsirphy.Scenario: self
Note:
If un-registered scenario name was specified, new scenario will be created.
Future phases will be always deleted.<|endoftext|> |
879bb450c787ea79b06519c3c9b11908283aa261272fa1e0be3f91d860fa5267 | def _delete_series(self, name):
'\n Delete a scenario or initialise main scenario.\n\n Args:\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n '
if (name == self.MAIN):
self[self.MAIN] = self._tracker(self.MAIN).delete_all()
else:
self._tracker_dict.pop(name)
return self | Delete a scenario or initialise main scenario.
Args:
name (str): name of phase series
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | _delete_series | fadelrahman31/modified-covsirphhy | 0 | python | def _delete_series(self, name):
'\n Delete a scenario or initialise main scenario.\n\n Args:\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n '
if (name == self.MAIN):
self[self.MAIN] = self._tracker(self.MAIN).delete_all()
else:
self._tracker_dict.pop(name)
return self | def _delete_series(self, name):
'\n Delete a scenario or initialise main scenario.\n\n Args:\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n '
if (name == self.MAIN):
self[self.MAIN] = self._tracker(self.MAIN).delete_all()
else:
self._tracker_dict.pop(name)
return self<|docstring|>Delete a scenario or initialise main scenario.
Args:
name (str): name of phase series
Returns:
covsirphy.Scenario: self<|endoftext|> |
98f3d8ae3d830f1a5fd65cbfc56fc557338a3666c6f9cf5ea45863e1a2a76015 | def delete(self, phases=None, name='Main'):
"\n Delete phases.\n\n Args:\n phase (list[str] or None): phase names, or ['last']\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @phases is None, the phase series will be deleted.\n When @phase is '0th', disable 0th phase. 0th phase will not be deleted.\n If the last phase is included in @phases, the dates will be released from phases.\n If the last phase is not included, the dates will be assigned to the previous phase.\n "
if (phases is None):
return self._delete_series(name)
tracker = self._tracker(name)
self[name] = tracker.delete(phases=phases)
return self | Delete phases.
Args:
phase (list[str] or None): phase names, or ['last']
name (str): name of phase series
Returns:
covsirphy.Scenario: self
Note:
If @phases is None, the phase series will be deleted.
When @phase is '0th', disable 0th phase. 0th phase will not be deleted.
If the last phase is included in @phases, the dates will be released from phases.
If the last phase is not included, the dates will be assigned to the previous phase. | covsirphy/analysis/scenario.py | delete | fadelrahman31/modified-covsirphhy | 0 | python | def delete(self, phases=None, name='Main'):
"\n Delete phases.\n\n Args:\n phase (list[str] or None): phase names, or ['last']\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @phases is None, the phase series will be deleted.\n When @phase is '0th', disable 0th phase. 0th phase will not be deleted.\n If the last phase is included in @phases, the dates will be released from phases.\n If the last phase is not included, the dates will be assigned to the previous phase.\n "
if (phases is None):
return self._delete_series(name)
tracker = self._tracker(name)
self[name] = tracker.delete(phases=phases)
return self | def delete(self, phases=None, name='Main'):
"\n Delete phases.\n\n Args:\n phase (list[str] or None): phase names, or ['last']\n name (str): name of phase series\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @phases is None, the phase series will be deleted.\n When @phase is '0th', disable 0th phase. 0th phase will not be deleted.\n If the last phase is included in @phases, the dates will be released from phases.\n If the last phase is not included, the dates will be assigned to the previous phase.\n "
if (phases is None):
return self._delete_series(name)
tracker = self._tracker(name)
self[name] = tracker.delete(phases=phases)
return self<|docstring|>Delete phases.
Args:
phase (list[str] or None): phase names, or ['last']
name (str): name of phase series
Returns:
covsirphy.Scenario: self
Note:
If @phases is None, the phase series will be deleted.
When @phase is '0th', disable 0th phase. 0th phase will not be deleted.
If the last phase is included in @phases, the dates will be released from phases.
If the last phase is not included, the dates will be assigned to the previous phase.<|endoftext|> |
cd56059394c464d8ef384fb69cae284c51f64427bc152cf2e6ed0d8b6cd8381d | def disable(self, phases, name='Main'):
'\n The phases will be disabled and removed from summary.\n\n Args:\n phase (list[str] or None): phase names or None (all enabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).disable(phases)
return self | The phases will be disabled and removed from summary.
Args:
phase (list[str] or None): phase names or None (all enabled phases)
name (str): scenario name
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | disable | fadelrahman31/modified-covsirphhy | 0 | python | def disable(self, phases, name='Main'):
'\n The phases will be disabled and removed from summary.\n\n Args:\n phase (list[str] or None): phase names or None (all enabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).disable(phases)
return self | def disable(self, phases, name='Main'):
'\n The phases will be disabled and removed from summary.\n\n Args:\n phase (list[str] or None): phase names or None (all enabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).disable(phases)
return self<|docstring|>The phases will be disabled and removed from summary.
Args:
phase (list[str] or None): phase names or None (all enabled phases)
name (str): scenario name
Returns:
covsirphy.Scenario: self<|endoftext|> |
57a6655bd79ddfb07b6cf6386973540764bfbd95c2af54b21ee310f6f7acbb31 | def enable(self, phases, name='Main'):
'\n The phases will be enabled and appear in summary.\n\n Args:\n phase (list[str] or None): phase names or None (all disabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).enable(phases)
return self | The phases will be enabled and appear in summary.
Args:
phase (list[str] or None): phase names or None (all disabled phases)
name (str): scenario name
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | enable | fadelrahman31/modified-covsirphhy | 0 | python | def enable(self, phases, name='Main'):
'\n The phases will be enabled and appear in summary.\n\n Args:\n phase (list[str] or None): phase names or None (all disabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).enable(phases)
return self | def enable(self, phases, name='Main'):
'\n The phases will be enabled and appear in summary.\n\n Args:\n phase (list[str] or None): phase names or None (all disabled phases)\n name (str): scenario name\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).enable(phases)
return self<|docstring|>The phases will be enabled and appear in summary.
Args:
phase (list[str] or None): phase names or None (all disabled phases)
name (str): scenario name
Returns:
covsirphy.Scenario: self<|endoftext|> |
5d68e2042f0b0b87c4952a11bd73b656c734612be60685808a7b5400b0a19c64 | def combine(self, phases, name='Main', population=None, **kwargs):
'\n Combine the sequential phases as one phase.\n New phase name will be automatically determined.\n\n Args:\n phases (list[str]): list of phases\n name (str, optional): name of phase series\n population (int): population value of the start date\n kwargs: keyword arguments to save as phase information\n\n Raises:\n TypeError: @phases is not a list\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).combine(phases=phases, population=population, **kwargs)
return self | Combine the sequential phases as one phase.
New phase name will be automatically determined.
Args:
phases (list[str]): list of phases
name (str, optional): name of phase series
population (int): population value of the start date
kwargs: keyword arguments to save as phase information
Raises:
TypeError: @phases is not a list
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | combine | fadelrahman31/modified-covsirphhy | 0 | python | def combine(self, phases, name='Main', population=None, **kwargs):
'\n Combine the sequential phases as one phase.\n New phase name will be automatically determined.\n\n Args:\n phases (list[str]): list of phases\n name (str, optional): name of phase series\n population (int): population value of the start date\n kwargs: keyword arguments to save as phase information\n\n Raises:\n TypeError: @phases is not a list\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).combine(phases=phases, population=population, **kwargs)
return self | def combine(self, phases, name='Main', population=None, **kwargs):
'\n Combine the sequential phases as one phase.\n New phase name will be automatically determined.\n\n Args:\n phases (list[str]): list of phases\n name (str, optional): name of phase series\n population (int): population value of the start date\n kwargs: keyword arguments to save as phase information\n\n Raises:\n TypeError: @phases is not a list\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).combine(phases=phases, population=population, **kwargs)
return self<|docstring|>Combine the sequential phases as one phase.
New phase name will be automatically determined.
Args:
phases (list[str]): list of phases
name (str, optional): name of phase series
population (int): population value of the start date
kwargs: keyword arguments to save as phase information
Raises:
TypeError: @phases is not a list
Returns:
covsirphy.Scenario: self<|endoftext|> |
daabfc96694faaf8b801e750b27d9131fb9cf59d5890f1bbc4829ebf5b2544f5 | def separate(self, date, name='Main', population=None, **kwargs):
'\n Create a new phase with the change point.\n New phase name will be automatically determined.\n\n Args:\n date (str): change point, i.e. start date of the new phase\n name (str): scenario name\n population (int): population value of the change point\n kwargs: keyword arguments of PhaseUnit.set_ode() if update is necessary\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).separate(date=date, population=population, **kwargs)
return self | Create a new phase with the change point.
New phase name will be automatically determined.
Args:
date (str): change point, i.e. start date of the new phase
name (str): scenario name
population (int): population value of the change point
kwargs: keyword arguments of PhaseUnit.set_ode() if update is necessary
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | separate | fadelrahman31/modified-covsirphhy | 0 | python | def separate(self, date, name='Main', population=None, **kwargs):
'\n Create a new phase with the change point.\n New phase name will be automatically determined.\n\n Args:\n date (str): change point, i.e. start date of the new phase\n name (str): scenario name\n population (int): population value of the change point\n kwargs: keyword arguments of PhaseUnit.set_ode() if update is necessary\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).separate(date=date, population=population, **kwargs)
return self | def separate(self, date, name='Main', population=None, **kwargs):
'\n Create a new phase with the change point.\n New phase name will be automatically determined.\n\n Args:\n date (str): change point, i.e. start date of the new phase\n name (str): scenario name\n population (int): population value of the change point\n kwargs: keyword arguments of PhaseUnit.set_ode() if update is necessary\n\n Returns:\n covsirphy.Scenario: self\n '
self[name] = self._tracker(name).separate(date=date, population=population, **kwargs)
return self<|docstring|>Create a new phase with the change point.
New phase name will be automatically determined.
Args:
date (str): change point, i.e. start date of the new phase
name (str): scenario name
population (int): population value of the change point
kwargs: keyword arguments of PhaseUnit.set_ode() if update is necessary
Returns:
covsirphy.Scenario: self<|endoftext|> |
5414f0d80a25d93e860863c2756e671113c059adcc04fa7bcafc4df342d1d6dd | def _summary(self, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
if (name is None):
if (len(self._tracker_dict.keys()) > 1):
dataframes = []
for (_name, tracker) in self._tracker_dict.items():
summary_df = tracker.series.summary()
summary_df = summary_df.rename_axis(self.PHASE)
summary_df[self.SERIES] = _name
dataframes.append(summary_df.reset_index())
df = pd.concat(dataframes, ignore_index=True, sort=False)
return df.set_index([self.SERIES, self.PHASE])
name = self.MAIN
return self._tracker(name).series.summary() | Summarize the series of phases and return a dataframe.
Args:
name (str): phase series name
- name of alternative phase series registered by Scenario.add()
- if None, all phase series will be shown
Returns:
pandas.DataFrame:
- if @name not None, as the same as PhaseSeries().summary()
- if @name is None, index will be phase series name and phase name
Note:
If 'Main' was used as @name, main PhaseSeries will be used. | covsirphy/analysis/scenario.py | _summary | fadelrahman31/modified-covsirphhy | 0 | python | def _summary(self, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
if (name is None):
if (len(self._tracker_dict.keys()) > 1):
dataframes = []
for (_name, tracker) in self._tracker_dict.items():
summary_df = tracker.series.summary()
summary_df = summary_df.rename_axis(self.PHASE)
summary_df[self.SERIES] = _name
dataframes.append(summary_df.reset_index())
df = pd.concat(dataframes, ignore_index=True, sort=False)
return df.set_index([self.SERIES, self.PHASE])
name = self.MAIN
return self._tracker(name).series.summary() | def _summary(self, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
if (name is None):
if (len(self._tracker_dict.keys()) > 1):
dataframes = []
for (_name, tracker) in self._tracker_dict.items():
summary_df = tracker.series.summary()
summary_df = summary_df.rename_axis(self.PHASE)
summary_df[self.SERIES] = _name
dataframes.append(summary_df.reset_index())
df = pd.concat(dataframes, ignore_index=True, sort=False)
return df.set_index([self.SERIES, self.PHASE])
name = self.MAIN
return self._tracker(name).series.summary()<|docstring|>Summarize the series of phases and return a dataframe.
Args:
name (str): phase series name
- name of alternative phase series registered by Scenario.add()
- if None, all phase series will be shown
Returns:
pandas.DataFrame:
- if @name not None, as the same as PhaseSeries().summary()
- if @name is None, index will be phase series name and phase name
Note:
If 'Main' was used as @name, main PhaseSeries will be used.<|endoftext|> |
a1ad05ba2b3c5bd8a63507b2e0c26379909383b91c4ec85ad837068bcd321420 | def summary(self, columns=None, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n columns (list[str] or None): columns to show\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n If @columns is None, all columns will be shown.\n "
df = self._summary(name=name).dropna(how='all', axis=1).fillna(self.UNKNOWN)
all_cols = df.columns.tolist()
if (columns is not None):
self._ensure_list(columns, all_cols, name='columns')
return df.loc[(:, columns)]
right_set = set([*Evaluator.metrics(), self.TRIALS, self.RUNTIME])
left_cols = [col for col in all_cols if (col not in right_set)]
right_cols = [col for col in all_cols if (col in right_set)]
return df.loc[(:, (left_cols + right_cols))] | Summarize the series of phases and return a dataframe.
Args:
name (str): phase series name
- name of alternative phase series registered by Scenario.add()
- if None, all phase series will be shown
columns (list[str] or None): columns to show
Returns:
pandas.DataFrame:
- if @name not None, as the same as PhaseSeries().summary()
- if @name is None, index will be phase series name and phase name
Note:
If 'Main' was used as @name, main PhaseSeries will be used.
If @columns is None, all columns will be shown. | covsirphy/analysis/scenario.py | summary | fadelrahman31/modified-covsirphhy | 0 | python | def summary(self, columns=None, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n columns (list[str] or None): columns to show\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n If @columns is None, all columns will be shown.\n "
df = self._summary(name=name).dropna(how='all', axis=1).fillna(self.UNKNOWN)
all_cols = df.columns.tolist()
if (columns is not None):
self._ensure_list(columns, all_cols, name='columns')
return df.loc[(:, columns)]
right_set = set([*Evaluator.metrics(), self.TRIALS, self.RUNTIME])
left_cols = [col for col in all_cols if (col not in right_set)]
right_cols = [col for col in all_cols if (col in right_set)]
return df.loc[(:, (left_cols + right_cols))] | def summary(self, columns=None, name=None):
"\n Summarize the series of phases and return a dataframe.\n\n Args:\n name (str): phase series name\n - name of alternative phase series registered by Scenario.add()\n - if None, all phase series will be shown\n columns (list[str] or None): columns to show\n\n Returns:\n pandas.DataFrame:\n - if @name not None, as the same as PhaseSeries().summary()\n - if @name is None, index will be phase series name and phase name\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n If @columns is None, all columns will be shown.\n "
df = self._summary(name=name).dropna(how='all', axis=1).fillna(self.UNKNOWN)
all_cols = df.columns.tolist()
if (columns is not None):
self._ensure_list(columns, all_cols, name='columns')
return df.loc[(:, columns)]
right_set = set([*Evaluator.metrics(), self.TRIALS, self.RUNTIME])
left_cols = [col for col in all_cols if (col not in right_set)]
right_cols = [col for col in all_cols if (col in right_set)]
return df.loc[(:, (left_cols + right_cols))]<|docstring|>Summarize the series of phases and return a dataframe.
Args:
name (str): phase series name
- name of alternative phase series registered by Scenario.add()
- if None, all phase series will be shown
columns (list[str] or None): columns to show
Returns:
pandas.DataFrame:
- if @name not None, as the same as PhaseSeries().summary()
- if @name is None, index will be phase series name and phase name
Note:
If 'Main' was used as @name, main PhaseSeries will be used.
If @columns is None, all columns will be shown.<|endoftext|> |
1fcbd5c2b546f5f131c91ce45616881c639a9e31f1b2598968dc7d48820e61a2 | def trend(self, min_size=None, force=True, name='Main', show_figure=True, filename=None, **kwargs):
'\n Perform S-R trend analysis and set phases.\n\n Args:\n min_size (int or None): minimum value of phase length [days] (over 2) or None (equal to max of 7 and delay period)\n force (bool): if True, change points will be over-written\n name (str): phase series name\n show_figure (bool): if True, show the result as a figure\n filename (str): filename of the figure, or None (display)\n kwargs: keyword arguments of\n - covsirphy.TrendDetector() and covsirphy.TrendDetector.sr()\n - covsirphy.trend_plot()\n - Scenario.estimate_delay()\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @min_size is None, this will be thw max value of 7 days and delay period calculated with .estimate_delay() method.\n '
if ('n_points' in kwargs.keys()):
raise ValueError('@n_points argument is un-necessary because the number of change points will be automatically determined.')
try:
include_init_phase = kwargs.pop('include_init_phase')
warnings.warn("@include_init_phase was deprecated. Please use Scenario.disable('0th').", DeprecationWarning, stacklevel=2)
except KeyError:
include_init_phase = True
try:
force = kwargs.pop('set_phases')
except KeyError:
pass
if (min_size is None):
try:
(delay, _) = self.estimate_delay(**find_args(self.estimate_delay, **kwargs))
except KeyError:
delay = 7
min_size = max(7, delay)
self._ensure_int_range(min_size, name='min_size', value_range=(2, None))
kwargs['min_size'] = min_size
tracker = self._tracker(name)
if ((not self._interactive) and (filename is None)):
show_figure = False
filename = (None if self._interactive else filename)
self[name] = tracker.trend(force=force, show_figure=show_figure, filename=filename, **kwargs)
if (not include_init_phase):
self[name] = tracker.disable(phases=['0th'])
return self | Perform S-R trend analysis and set phases.
Args:
min_size (int or None): minimum value of phase length [days] (over 2) or None (equal to max of 7 and delay period)
force (bool): if True, change points will be over-written
name (str): phase series name
show_figure (bool): if True, show the result as a figure
filename (str): filename of the figure, or None (display)
kwargs: keyword arguments of
- covsirphy.TrendDetector() and covsirphy.TrendDetector.sr()
- covsirphy.trend_plot()
- Scenario.estimate_delay()
Returns:
covsirphy.Scenario: self
Note:
If @min_size is None, this will be thw max value of 7 days and delay period calculated with .estimate_delay() method. | covsirphy/analysis/scenario.py | trend | fadelrahman31/modified-covsirphhy | 0 | python | def trend(self, min_size=None, force=True, name='Main', show_figure=True, filename=None, **kwargs):
'\n Perform S-R trend analysis and set phases.\n\n Args:\n min_size (int or None): minimum value of phase length [days] (over 2) or None (equal to max of 7 and delay period)\n force (bool): if True, change points will be over-written\n name (str): phase series name\n show_figure (bool): if True, show the result as a figure\n filename (str): filename of the figure, or None (display)\n kwargs: keyword arguments of\n - covsirphy.TrendDetector() and covsirphy.TrendDetector.sr()\n - covsirphy.trend_plot()\n - Scenario.estimate_delay()\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @min_size is None, this will be thw max value of 7 days and delay period calculated with .estimate_delay() method.\n '
if ('n_points' in kwargs.keys()):
raise ValueError('@n_points argument is un-necessary because the number of change points will be automatically determined.')
try:
include_init_phase = kwargs.pop('include_init_phase')
warnings.warn("@include_init_phase was deprecated. Please use Scenario.disable('0th').", DeprecationWarning, stacklevel=2)
except KeyError:
include_init_phase = True
try:
force = kwargs.pop('set_phases')
except KeyError:
pass
if (min_size is None):
try:
(delay, _) = self.estimate_delay(**find_args(self.estimate_delay, **kwargs))
except KeyError:
delay = 7
min_size = max(7, delay)
self._ensure_int_range(min_size, name='min_size', value_range=(2, None))
kwargs['min_size'] = min_size
tracker = self._tracker(name)
if ((not self._interactive) and (filename is None)):
show_figure = False
filename = (None if self._interactive else filename)
self[name] = tracker.trend(force=force, show_figure=show_figure, filename=filename, **kwargs)
if (not include_init_phase):
self[name] = tracker.disable(phases=['0th'])
return self | def trend(self, min_size=None, force=True, name='Main', show_figure=True, filename=None, **kwargs):
'\n Perform S-R trend analysis and set phases.\n\n Args:\n min_size (int or None): minimum value of phase length [days] (over 2) or None (equal to max of 7 and delay period)\n force (bool): if True, change points will be over-written\n name (str): phase series name\n show_figure (bool): if True, show the result as a figure\n filename (str): filename of the figure, or None (display)\n kwargs: keyword arguments of\n - covsirphy.TrendDetector() and covsirphy.TrendDetector.sr()\n - covsirphy.trend_plot()\n - Scenario.estimate_delay()\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n If @min_size is None, this will be thw max value of 7 days and delay period calculated with .estimate_delay() method.\n '
if ('n_points' in kwargs.keys()):
raise ValueError('@n_points argument is un-necessary because the number of change points will be automatically determined.')
try:
include_init_phase = kwargs.pop('include_init_phase')
warnings.warn("@include_init_phase was deprecated. Please use Scenario.disable('0th').", DeprecationWarning, stacklevel=2)
except KeyError:
include_init_phase = True
try:
force = kwargs.pop('set_phases')
except KeyError:
pass
if (min_size is None):
try:
(delay, _) = self.estimate_delay(**find_args(self.estimate_delay, **kwargs))
except KeyError:
delay = 7
min_size = max(7, delay)
self._ensure_int_range(min_size, name='min_size', value_range=(2, None))
kwargs['min_size'] = min_size
tracker = self._tracker(name)
if ((not self._interactive) and (filename is None)):
show_figure = False
filename = (None if self._interactive else filename)
self[name] = tracker.trend(force=force, show_figure=show_figure, filename=filename, **kwargs)
if (not include_init_phase):
self[name] = tracker.disable(phases=['0th'])
return self<|docstring|>Perform S-R trend analysis and set phases.
Args:
min_size (int or None): minimum value of phase length [days] (over 2) or None (equal to max of 7 and delay period)
force (bool): if True, change points will be over-written
name (str): phase series name
show_figure (bool): if True, show the result as a figure
filename (str): filename of the figure, or None (display)
kwargs: keyword arguments of
- covsirphy.TrendDetector() and covsirphy.TrendDetector.sr()
- covsirphy.trend_plot()
- Scenario.estimate_delay()
Returns:
covsirphy.Scenario: self
Note:
If @min_size is None, this will be thw max value of 7 days and delay period calculated with .estimate_delay() method.<|endoftext|> |
93c0f98e223f0f6348f2c39b2adf446d4bb4bcd7c4d4c0bc33f83a07bdaaf829 | def estimate(self, model, phases=None, name='Main', n_jobs=(- 1), **kwargs):
"\n Perform parameter estimation for each phases.\n\n Args:\n model (covsirphy.ModelBase): ODE model\n phases (list[str]): list of phase names, like 1st, 2nd...\n name (str): phase series name\n n_jobs (int): the number of parallel jobs or -1 (CPU count)\n kwargs: keyword arguments of model parameters and covsirphy.Estimator.run()\n\n Note:\n - If 'Main' was used as @name, main PhaseSeries will be used.\n - If @name phase was not registered, new PhaseSeries will be created.\n - If @phases is None, all past phase will be used.\n - Phases with estimated parameter values will be ignored.\n - In kwargs, tau value cannot be included.\n "
if (self.TAU in kwargs):
raise ValueError('@tau must be specified when scenario = Scenario(), and cannot be specified here.')
(self.tau, self[name]) = self._tracker(name).estimate(model=model, phases=phases, n_jobs=n_jobs, **kwargs) | Perform parameter estimation for each phases.
Args:
model (covsirphy.ModelBase): ODE model
phases (list[str]): list of phase names, like 1st, 2nd...
name (str): phase series name
n_jobs (int): the number of parallel jobs or -1 (CPU count)
kwargs: keyword arguments of model parameters and covsirphy.Estimator.run()
Note:
- If 'Main' was used as @name, main PhaseSeries will be used.
- If @name phase was not registered, new PhaseSeries will be created.
- If @phases is None, all past phase will be used.
- Phases with estimated parameter values will be ignored.
- In kwargs, tau value cannot be included. | covsirphy/analysis/scenario.py | estimate | fadelrahman31/modified-covsirphhy | 0 | python | def estimate(self, model, phases=None, name='Main', n_jobs=(- 1), **kwargs):
"\n Perform parameter estimation for each phases.\n\n Args:\n model (covsirphy.ModelBase): ODE model\n phases (list[str]): list of phase names, like 1st, 2nd...\n name (str): phase series name\n n_jobs (int): the number of parallel jobs or -1 (CPU count)\n kwargs: keyword arguments of model parameters and covsirphy.Estimator.run()\n\n Note:\n - If 'Main' was used as @name, main PhaseSeries will be used.\n - If @name phase was not registered, new PhaseSeries will be created.\n - If @phases is None, all past phase will be used.\n - Phases with estimated parameter values will be ignored.\n - In kwargs, tau value cannot be included.\n "
if (self.TAU in kwargs):
raise ValueError('@tau must be specified when scenario = Scenario(), and cannot be specified here.')
(self.tau, self[name]) = self._tracker(name).estimate(model=model, phases=phases, n_jobs=n_jobs, **kwargs) | def estimate(self, model, phases=None, name='Main', n_jobs=(- 1), **kwargs):
"\n Perform parameter estimation for each phases.\n\n Args:\n model (covsirphy.ModelBase): ODE model\n phases (list[str]): list of phase names, like 1st, 2nd...\n name (str): phase series name\n n_jobs (int): the number of parallel jobs or -1 (CPU count)\n kwargs: keyword arguments of model parameters and covsirphy.Estimator.run()\n\n Note:\n - If 'Main' was used as @name, main PhaseSeries will be used.\n - If @name phase was not registered, new PhaseSeries will be created.\n - If @phases is None, all past phase will be used.\n - Phases with estimated parameter values will be ignored.\n - In kwargs, tau value cannot be included.\n "
if (self.TAU in kwargs):
raise ValueError('@tau must be specified when scenario = Scenario(), and cannot be specified here.')
(self.tau, self[name]) = self._tracker(name).estimate(model=model, phases=phases, n_jobs=n_jobs, **kwargs)<|docstring|>Perform parameter estimation for each phases.
Args:
model (covsirphy.ModelBase): ODE model
phases (list[str]): list of phase names, like 1st, 2nd...
name (str): phase series name
n_jobs (int): the number of parallel jobs or -1 (CPU count)
kwargs: keyword arguments of model parameters and covsirphy.Estimator.run()
Note:
- If 'Main' was used as @name, main PhaseSeries will be used.
- If @name phase was not registered, new PhaseSeries will be created.
- If @phases is None, all past phase will be used.
- Phases with estimated parameter values will be ignored.
- In kwargs, tau value cannot be included.<|endoftext|> |
65b28b321074f29a5de0ab3ae78330a6c3ffd3ae077067ec757d80639ba61c81 | def phase_estimator(self, phase, name='Main'):
'\n Return the estimator of the phase.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n\n Return:\n covsirphy.Estimator: estimator of the phase\n '
estimator = self._tracker_dict[name].series.unit(phase).estimator
if (estimator is None):
raise UnExecutedError(f'Scenario.estimate(model, phases=["{phase}"], name={name})')
return estimator | Return the estimator of the phase.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
Return:
covsirphy.Estimator: estimator of the phase | covsirphy/analysis/scenario.py | phase_estimator | fadelrahman31/modified-covsirphhy | 0 | python | def phase_estimator(self, phase, name='Main'):
'\n Return the estimator of the phase.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n\n Return:\n covsirphy.Estimator: estimator of the phase\n '
estimator = self._tracker_dict[name].series.unit(phase).estimator
if (estimator is None):
raise UnExecutedError(f'Scenario.estimate(model, phases=["{phase}"], name={name})')
return estimator | def phase_estimator(self, phase, name='Main'):
'\n Return the estimator of the phase.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n\n Return:\n covsirphy.Estimator: estimator of the phase\n '
estimator = self._tracker_dict[name].series.unit(phase).estimator
if (estimator is None):
raise UnExecutedError(f'Scenario.estimate(model, phases=["{phase}"], name={name})')
return estimator<|docstring|>Return the estimator of the phase.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
Return:
covsirphy.Estimator: estimator of the phase<|endoftext|> |
7dbfa312e81916d0831fb12f48c06d537674a04add3f7dd9640e945ae0aac7e7 | def estimate_history(self, phase, name='Main', **kwargs):
"\n Show the history of optimization.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.history()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.history(**kwargs) | Show the history of optimization.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
kwargs: keyword arguments of covsirphy.Estimator.history()
Note:
If 'Main' was used as @name, main PhaseSeries will be used. | covsirphy/analysis/scenario.py | estimate_history | fadelrahman31/modified-covsirphhy | 0 | python | def estimate_history(self, phase, name='Main', **kwargs):
"\n Show the history of optimization.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.history()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.history(**kwargs) | def estimate_history(self, phase, name='Main', **kwargs):
"\n Show the history of optimization.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.history()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.history(**kwargs)<|docstring|>Show the history of optimization.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
kwargs: keyword arguments of covsirphy.Estimator.history()
Note:
If 'Main' was used as @name, main PhaseSeries will be used.<|endoftext|> |
66ff6a7ee5feaab72f92c8cb14584b8289f3c0735b04180e71387df9f27f87e8 | def estimate_accuracy(self, phase, name='Main', **kwargs):
"\n Show the accuracy as a figure.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.accuracy()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.accuracy(**kwargs) | Show the accuracy as a figure.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
kwargs: keyword arguments of covsirphy.Estimator.accuracy()
Note:
If 'Main' was used as @name, main PhaseSeries will be used. | covsirphy/analysis/scenario.py | estimate_accuracy | fadelrahman31/modified-covsirphhy | 0 | python | def estimate_accuracy(self, phase, name='Main', **kwargs):
"\n Show the accuracy as a figure.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.accuracy()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.accuracy(**kwargs) | def estimate_accuracy(self, phase, name='Main', **kwargs):
"\n Show the accuracy as a figure.\n\n Args:\n phase (str): phase name, like 1st, 2nd...\n name (str): phase series name\n kwargs: keyword arguments of covsirphy.Estimator.accuracy()\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
estimator = self.phase_estimator(phase=phase, name=name)
estimator.accuracy(**kwargs)<|docstring|>Show the accuracy as a figure.
Args:
phase (str): phase name, like 1st, 2nd...
name (str): phase series name
kwargs: keyword arguments of covsirphy.Estimator.accuracy()
Note:
If 'Main' was used as @name, main PhaseSeries will be used.<|endoftext|> |
6e47c48924952d4b456158bd2ed0e0f7e06c65a5e0bd2f2089d5daf7a4665b12 | def simulate(self, variables=None, phases=None, name='Main', y0_dict=None, **kwargs):
"\n Simulate ODE models with set/estimated parameter values and show it as a figure.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name. If 'Main', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Country (str): country/region name\n - Province (str): province/prefecture/state name\n - Variables of the main dataset (int): Confirmed etc.\n "
tracker = copy.deepcopy(self._tracker(name))
if (phases is not None):
tracker.disable(phases=None)
tracker.enable(phases=phases)
try:
sim_df = tracker.simulate(y0_dict=y0_dict)
except UnExecutedError:
raise UnExecutedError('Scenario.trend() or Scenario.add(), and Scenario.estimate(model)') from None
df = sim_df.set_index(self.DATE)
variables = self._convert_variables(variables, candidates=self.VALUE_COLUMNS)
title = f'{self.area}: Simulated number of cases ({name} scenario)'
self.line_plot(df=df.loc[(:, variables)], title=title, y_integer=True, v=tracker.change_dates(), **kwargs)
return sim_df | Simulate ODE models with set/estimated parameter values and show it as a figure.
Args:
variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())
phases (list[str] or None): phases to shoe or None (all phases)
name (str): phase series name. If 'Main', main PhaseSeries will be used
y0_dict(dict[str, float] or None): dictionary of initial values of variables
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame
Index
reset index
Columns
- Date (pd.Timestamp): Observation date
- Country (str): country/region name
- Province (str): province/prefecture/state name
- Variables of the main dataset (int): Confirmed etc. | covsirphy/analysis/scenario.py | simulate | fadelrahman31/modified-covsirphhy | 0 | python | def simulate(self, variables=None, phases=None, name='Main', y0_dict=None, **kwargs):
"\n Simulate ODE models with set/estimated parameter values and show it as a figure.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name. If 'Main', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Country (str): country/region name\n - Province (str): province/prefecture/state name\n - Variables of the main dataset (int): Confirmed etc.\n "
tracker = copy.deepcopy(self._tracker(name))
if (phases is not None):
tracker.disable(phases=None)
tracker.enable(phases=phases)
try:
sim_df = tracker.simulate(y0_dict=y0_dict)
except UnExecutedError:
raise UnExecutedError('Scenario.trend() or Scenario.add(), and Scenario.estimate(model)') from None
df = sim_df.set_index(self.DATE)
variables = self._convert_variables(variables, candidates=self.VALUE_COLUMNS)
title = f'{self.area}: Simulated number of cases ({name} scenario)'
self.line_plot(df=df.loc[(:, variables)], title=title, y_integer=True, v=tracker.change_dates(), **kwargs)
return sim_df | def simulate(self, variables=None, phases=None, name='Main', y0_dict=None, **kwargs):
"\n Simulate ODE models with set/estimated parameter values and show it as a figure.\n\n Args:\n variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name. If 'Main', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Country (str): country/region name\n - Province (str): province/prefecture/state name\n - Variables of the main dataset (int): Confirmed etc.\n "
tracker = copy.deepcopy(self._tracker(name))
if (phases is not None):
tracker.disable(phases=None)
tracker.enable(phases=phases)
try:
sim_df = tracker.simulate(y0_dict=y0_dict)
except UnExecutedError:
raise UnExecutedError('Scenario.trend() or Scenario.add(), and Scenario.estimate(model)') from None
df = sim_df.set_index(self.DATE)
variables = self._convert_variables(variables, candidates=self.VALUE_COLUMNS)
title = f'{self.area}: Simulated number of cases ({name} scenario)'
self.line_plot(df=df.loc[(:, variables)], title=title, y_integer=True, v=tracker.change_dates(), **kwargs)
return sim_df<|docstring|>Simulate ODE models with set/estimated parameter values and show it as a figure.
Args:
variables (list[str] or str or None): variable names or abbreviated names (as the same as Scenario.records())
phases (list[str] or None): phases to shoe or None (all phases)
name (str): phase series name. If 'Main', main PhaseSeries will be used
y0_dict(dict[str, float] or None): dictionary of initial values of variables
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame
Index
reset index
Columns
- Date (pd.Timestamp): Observation date
- Country (str): country/region name
- Province (str): province/prefecture/state name
- Variables of the main dataset (int): Confirmed etc.<|endoftext|> |
495c0087929ee196b2048f745519b6368c385b403ac7e953290799267ec750d5 | def get(self, param, phase='last', name='Main'):
"\n Get the parameter value of the phase.\n\n Args:\n param (str): parameter name (columns in self.summary())\n phase (str): phase name or 'last'\n - if 'last', the value of the last phase will be returned\n name (str): phase series name\n\n Returns:\n str or int or float\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
df = self.summary(name=name)
if (param not in df.columns):
raise KeyError(f"@param must be in {', '.join(df.columns)}.")
if (phase == 'last'):
phase = df.index[(- 1)]
return df.loc[(phase, param)] | Get the parameter value of the phase.
Args:
param (str): parameter name (columns in self.summary())
phase (str): phase name or 'last'
- if 'last', the value of the last phase will be returned
name (str): phase series name
Returns:
str or int or float
Note:
If 'Main' was used as @name, main PhaseSeries will be used. | covsirphy/analysis/scenario.py | get | fadelrahman31/modified-covsirphhy | 0 | python | def get(self, param, phase='last', name='Main'):
"\n Get the parameter value of the phase.\n\n Args:\n param (str): parameter name (columns in self.summary())\n phase (str): phase name or 'last'\n - if 'last', the value of the last phase will be returned\n name (str): phase series name\n\n Returns:\n str or int or float\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
df = self.summary(name=name)
if (param not in df.columns):
raise KeyError(f"@param must be in {', '.join(df.columns)}.")
if (phase == 'last'):
phase = df.index[(- 1)]
return df.loc[(phase, param)] | def get(self, param, phase='last', name='Main'):
"\n Get the parameter value of the phase.\n\n Args:\n param (str): parameter name (columns in self.summary())\n phase (str): phase name or 'last'\n - if 'last', the value of the last phase will be returned\n name (str): phase series name\n\n Returns:\n str or int or float\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
df = self.summary(name=name)
if (param not in df.columns):
raise KeyError(f"@param must be in {', '.join(df.columns)}.")
if (phase == 'last'):
phase = df.index[(- 1)]
return df.loc[(phase, param)]<|docstring|>Get the parameter value of the phase.
Args:
param (str): parameter name (columns in self.summary())
phase (str): phase name or 'last'
- if 'last', the value of the last phase will be returned
name (str): phase series name
Returns:
str or int or float
Note:
If 'Main' was used as @name, main PhaseSeries will be used.<|endoftext|> |
55334616f86abedec1439909b279a4af7b40d1fc4a29381a303993d66692b4c5 | def _param_history(self, targets, name):
'\n Return the subset of summary dataframe to select the target of parameter history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n\n Returns:\n pandas.DataFrame: selected summary dataframe\n\n Raises:\n KeyError: targets are not in the columns of summary dataframe\n '
series = self._tracker_dict[name].series
model_set = {unit.model for unit in series}
model_set = (model_set - set([None]))
parameters = self.flatten([m.PARAMETERS for m in model_set])
day_params = self.flatten([m.DAY_PARAMETERS for m in model_set])
selectable_cols = [self.N, *parameters, self.RT, *day_params]
selectable_set = set(selectable_cols)
df = series.summary().replace(self.UNKNOWN, None)
if (not selectable_set.issubset(df.columns)):
raise UnExecutedError(f'Scenario.estimate(model, phases=None, name="{name}")')
targets = ([targets] if isinstance(targets, str) else targets)
targets = (targets or selectable_cols)
if (not set(targets).issubset(selectable_set)):
raise KeyError(f"@targets must be selected from {', '.join(selectable_cols)}.")
df = df.loc[(:, targets)].dropna(how='any', axis=0)
return df.astype(np.float64) | Return the subset of summary dataframe to select the target of parameter history.
Args:
targets (list[str] or str): parameters to show (Rt etc.)
name (str): phase series name
Returns:
pandas.DataFrame: selected summary dataframe
Raises:
KeyError: targets are not in the columns of summary dataframe | covsirphy/analysis/scenario.py | _param_history | fadelrahman31/modified-covsirphhy | 0 | python | def _param_history(self, targets, name):
'\n Return the subset of summary dataframe to select the target of parameter history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n\n Returns:\n pandas.DataFrame: selected summary dataframe\n\n Raises:\n KeyError: targets are not in the columns of summary dataframe\n '
series = self._tracker_dict[name].series
model_set = {unit.model for unit in series}
model_set = (model_set - set([None]))
parameters = self.flatten([m.PARAMETERS for m in model_set])
day_params = self.flatten([m.DAY_PARAMETERS for m in model_set])
selectable_cols = [self.N, *parameters, self.RT, *day_params]
selectable_set = set(selectable_cols)
df = series.summary().replace(self.UNKNOWN, None)
if (not selectable_set.issubset(df.columns)):
raise UnExecutedError(f'Scenario.estimate(model, phases=None, name="{name}")')
targets = ([targets] if isinstance(targets, str) else targets)
targets = (targets or selectable_cols)
if (not set(targets).issubset(selectable_set)):
raise KeyError(f"@targets must be selected from {', '.join(selectable_cols)}.")
df = df.loc[(:, targets)].dropna(how='any', axis=0)
return df.astype(np.float64) | def _param_history(self, targets, name):
'\n Return the subset of summary dataframe to select the target of parameter history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n\n Returns:\n pandas.DataFrame: selected summary dataframe\n\n Raises:\n KeyError: targets are not in the columns of summary dataframe\n '
series = self._tracker_dict[name].series
model_set = {unit.model for unit in series}
model_set = (model_set - set([None]))
parameters = self.flatten([m.PARAMETERS for m in model_set])
day_params = self.flatten([m.DAY_PARAMETERS for m in model_set])
selectable_cols = [self.N, *parameters, self.RT, *day_params]
selectable_set = set(selectable_cols)
df = series.summary().replace(self.UNKNOWN, None)
if (not selectable_set.issubset(df.columns)):
raise UnExecutedError(f'Scenario.estimate(model, phases=None, name="{name}")')
targets = ([targets] if isinstance(targets, str) else targets)
targets = (targets or selectable_cols)
if (not set(targets).issubset(selectable_set)):
raise KeyError(f"@targets must be selected from {', '.join(selectable_cols)}.")
df = df.loc[(:, targets)].dropna(how='any', axis=0)
return df.astype(np.float64)<|docstring|>Return the subset of summary dataframe to select the target of parameter history.
Args:
targets (list[str] or str): parameters to show (Rt etc.)
name (str): phase series name
Returns:
pandas.DataFrame: selected summary dataframe
Raises:
KeyError: targets are not in the columns of summary dataframe<|endoftext|> |
59c6122b98cbbb957ee34f729794ff917240d847e3b777d94e5488d3ce4aa5cc | @deprecate(old='Scenario.param_history(targets: list)', new='Scenario.history(target: str)', version='2.7.3-alpha')
def param_history(self, targets=None, name='Main', divide_by_first=True, show_figure=True, filename=None, show_box_plot=True, **kwargs):
"\n Return subset of summary and show a figure to show the history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n divide_by_first (bool): if True, divide the values by 1st phase's values\n show_box_plot (bool): if True, box plot. if False, line plot\n show_figure (bool): If True, show the result as a figure\n filename (str): filename of the figure, or None (show figure)\n kwargs: keyword arguments of pd.DataFrame.plot or line_plot()\n\n Returns:\n pandas.DataFrame\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
self._tracker(name)
df = self._param_history(targets, name)
if divide_by_first:
df = (df / df.iloc[(0, :)])
title = f'{self.area}: Ratio to 1st phase parameters ({name} scenario)'
else:
title = f'{self.area}: History of parameter values ({name} scenario)'
if (not show_figure):
return df
if show_box_plot:
h_values = ([1.0] if (divide_by_first or (self.RT in targets)) else None)
bar_plot(df, title=title, h=h_values, filename=filename, ylabel=None)
return df
return self.history_rate(params=targets, name=name, **kwargs) | Return subset of summary and show a figure to show the history.
Args:
targets (list[str] or str): parameters to show (Rt etc.)
name (str): phase series name
divide_by_first (bool): if True, divide the values by 1st phase's values
show_box_plot (bool): if True, box plot. if False, line plot
show_figure (bool): If True, show the result as a figure
filename (str): filename of the figure, or None (show figure)
kwargs: keyword arguments of pd.DataFrame.plot or line_plot()
Returns:
pandas.DataFrame
Note:
If 'Main' was used as @name, main PhaseSeries will be used. | covsirphy/analysis/scenario.py | param_history | fadelrahman31/modified-covsirphhy | 0 | python | @deprecate(old='Scenario.param_history(targets: list)', new='Scenario.history(target: str)', version='2.7.3-alpha')
def param_history(self, targets=None, name='Main', divide_by_first=True, show_figure=True, filename=None, show_box_plot=True, **kwargs):
"\n Return subset of summary and show a figure to show the history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n divide_by_first (bool): if True, divide the values by 1st phase's values\n show_box_plot (bool): if True, box plot. if False, line plot\n show_figure (bool): If True, show the result as a figure\n filename (str): filename of the figure, or None (show figure)\n kwargs: keyword arguments of pd.DataFrame.plot or line_plot()\n\n Returns:\n pandas.DataFrame\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
self._tracker(name)
df = self._param_history(targets, name)
if divide_by_first:
df = (df / df.iloc[(0, :)])
title = f'{self.area}: Ratio to 1st phase parameters ({name} scenario)'
else:
title = f'{self.area}: History of parameter values ({name} scenario)'
if (not show_figure):
return df
if show_box_plot:
h_values = ([1.0] if (divide_by_first or (self.RT in targets)) else None)
bar_plot(df, title=title, h=h_values, filename=filename, ylabel=None)
return df
return self.history_rate(params=targets, name=name, **kwargs) | @deprecate(old='Scenario.param_history(targets: list)', new='Scenario.history(target: str)', version='2.7.3-alpha')
def param_history(self, targets=None, name='Main', divide_by_first=True, show_figure=True, filename=None, show_box_plot=True, **kwargs):
"\n Return subset of summary and show a figure to show the history.\n\n Args:\n targets (list[str] or str): parameters to show (Rt etc.)\n name (str): phase series name\n divide_by_first (bool): if True, divide the values by 1st phase's values\n show_box_plot (bool): if True, box plot. if False, line plot\n show_figure (bool): If True, show the result as a figure\n filename (str): filename of the figure, or None (show figure)\n kwargs: keyword arguments of pd.DataFrame.plot or line_plot()\n\n Returns:\n pandas.DataFrame\n\n Note:\n If 'Main' was used as @name, main PhaseSeries will be used.\n "
self._tracker(name)
df = self._param_history(targets, name)
if divide_by_first:
df = (df / df.iloc[(0, :)])
title = f'{self.area}: Ratio to 1st phase parameters ({name} scenario)'
else:
title = f'{self.area}: History of parameter values ({name} scenario)'
if (not show_figure):
return df
if show_box_plot:
h_values = ([1.0] if (divide_by_first or (self.RT in targets)) else None)
bar_plot(df, title=title, h=h_values, filename=filename, ylabel=None)
return df
return self.history_rate(params=targets, name=name, **kwargs)<|docstring|>Return subset of summary and show a figure to show the history.
Args:
targets (list[str] or str): parameters to show (Rt etc.)
name (str): phase series name
divide_by_first (bool): if True, divide the values by 1st phase's values
show_box_plot (bool): if True, box plot. if False, line plot
show_figure (bool): If True, show the result as a figure
filename (str): filename of the figure, or None (show figure)
kwargs: keyword arguments of pd.DataFrame.plot or line_plot()
Returns:
pandas.DataFrame
Note:
If 'Main' was used as @name, main PhaseSeries will be used.<|endoftext|> |
8b5a7412f6351e343e25f8cbe0a5d04f996503aa241ce4df57388598dcc018a1 | def adjust_end(self):
'\n Adjust the last end dates of the registered scenarios, if necessary.\n\n Returns:\n covsirphy.Scenario: self\n '
current_dict = {name: self.date_obj(tracker.last_end_date()) for (name, tracker) in self._tracker_dict.items()}
adjusted_str = max(current_dict.values()).strftime(self.DATE_FORMAT)
for (name, _) in self._tracker_dict.items():
try:
self.add(end_date=adjusted_str, name=name)
except ValueError:
pass
return self | Adjust the last end dates of the registered scenarios, if necessary.
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | adjust_end | fadelrahman31/modified-covsirphhy | 0 | python | def adjust_end(self):
'\n Adjust the last end dates of the registered scenarios, if necessary.\n\n Returns:\n covsirphy.Scenario: self\n '
current_dict = {name: self.date_obj(tracker.last_end_date()) for (name, tracker) in self._tracker_dict.items()}
adjusted_str = max(current_dict.values()).strftime(self.DATE_FORMAT)
for (name, _) in self._tracker_dict.items():
try:
self.add(end_date=adjusted_str, name=name)
except ValueError:
pass
return self | def adjust_end(self):
'\n Adjust the last end dates of the registered scenarios, if necessary.\n\n Returns:\n covsirphy.Scenario: self\n '
current_dict = {name: self.date_obj(tracker.last_end_date()) for (name, tracker) in self._tracker_dict.items()}
adjusted_str = max(current_dict.values()).strftime(self.DATE_FORMAT)
for (name, _) in self._tracker_dict.items():
try:
self.add(end_date=adjusted_str, name=name)
except ValueError:
pass
return self<|docstring|>Adjust the last end dates of the registered scenarios, if necessary.
Returns:
covsirphy.Scenario: self<|endoftext|> |
c839db61bd10278eb86a67bc7f71c785077df21de03fe2f6a12b35a8f32b8f12 | def _describe(self, y0_dict=None):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n Index\n (int): scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n '
_dict = {}
for (name, _) in self._tracker_dict.items():
df = self.simulate(name=name, y0_dict=y0_dict, show_figure=False)
df = df.set_index(self.DATE)
cols = df.columns[:]
last_date = df.index[(- 1)]
max_ci = df[self.CI].max()
argmax_ci = df[self.CI].idxmax().strftime(self.DATE_FORMAT)
last_c = df.loc[(last_date, self.C)]
last_ci = df.loc[(last_date, self.CI)]
last_f = (df.loc[(last_date, self.F)] if (self.F in cols) else None)
last_date_str = last_date.strftime(self.DATE_FORMAT)
_dict[name] = {f'max({self.CI})': max_ci, f'argmax({self.CI})': argmax_ci, f'{self.C} on {last_date_str}': last_c, f'{self.CI} on {last_date_str}': last_ci, f'{self.F} on {last_date_str}': last_f}
return pd.DataFrame.from_dict(_dict, orient='index') | Describe representative values.
Args:
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame
Index
(int): scenario name
Columns
- max(Infected): max value of Infected
- argmax(Infected): the date when Infected shows max value
- Confirmed({date}): Confirmed on the next date of the last phase
- Infected({date}): Infected on the next date of the last phase
- Fatal({date}): Fatal on the next date of the last phase | covsirphy/analysis/scenario.py | _describe | fadelrahman31/modified-covsirphhy | 0 | python | def _describe(self, y0_dict=None):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n Index\n (int): scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n '
_dict = {}
for (name, _) in self._tracker_dict.items():
df = self.simulate(name=name, y0_dict=y0_dict, show_figure=False)
df = df.set_index(self.DATE)
cols = df.columns[:]
last_date = df.index[(- 1)]
max_ci = df[self.CI].max()
argmax_ci = df[self.CI].idxmax().strftime(self.DATE_FORMAT)
last_c = df.loc[(last_date, self.C)]
last_ci = df.loc[(last_date, self.CI)]
last_f = (df.loc[(last_date, self.F)] if (self.F in cols) else None)
last_date_str = last_date.strftime(self.DATE_FORMAT)
_dict[name] = {f'max({self.CI})': max_ci, f'argmax({self.CI})': argmax_ci, f'{self.C} on {last_date_str}': last_c, f'{self.CI} on {last_date_str}': last_ci, f'{self.F} on {last_date_str}': last_f}
return pd.DataFrame.from_dict(_dict, orient='index') | def _describe(self, y0_dict=None):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n Index\n (int): scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n '
_dict = {}
for (name, _) in self._tracker_dict.items():
df = self.simulate(name=name, y0_dict=y0_dict, show_figure=False)
df = df.set_index(self.DATE)
cols = df.columns[:]
last_date = df.index[(- 1)]
max_ci = df[self.CI].max()
argmax_ci = df[self.CI].idxmax().strftime(self.DATE_FORMAT)
last_c = df.loc[(last_date, self.C)]
last_ci = df.loc[(last_date, self.CI)]
last_f = (df.loc[(last_date, self.F)] if (self.F in cols) else None)
last_date_str = last_date.strftime(self.DATE_FORMAT)
_dict[name] = {f'max({self.CI})': max_ci, f'argmax({self.CI})': argmax_ci, f'{self.C} on {last_date_str}': last_c, f'{self.CI} on {last_date_str}': last_ci, f'{self.F} on {last_date_str}': last_f}
return pd.DataFrame.from_dict(_dict, orient='index')<|docstring|>Describe representative values.
Args:
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame
Index
(int): scenario name
Columns
- max(Infected): max value of Infected
- argmax(Infected): the date when Infected shows max value
- Confirmed({date}): Confirmed on the next date of the last phase
- Infected({date}): Infected on the next date of the last phase
- Fatal({date}): Fatal on the next date of the last phase<|endoftext|> |
55fc325f913c0ad5176c5fab84ac99c57c3ed1358ccac4c9ae234076a4f90a7e | def describe(self, y0_dict=None, with_rt=True):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n with_rt (bool): whether show the history of Rt values\n\n Returns:\n pandas.DataFrame:\n Index\n str: scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n - nth_Rt etc.: Rt value if the values are not the same values\n '
df = self._describe(y0_dict=y0_dict)
if ((not with_rt) or (len(self._tracker_dict) == 1)):
return df
rt_df = self.summary().reset_index()
rt_df = rt_df.pivot_table(index=self.SERIES, columns=self.PHASE, values=self.RT)
rt_df = rt_df.fillna(self.UNKNOWN)
rt_df = rt_df.loc[(:, (rt_df.nunique() > 1))]
cols = sorted(rt_df, key=self.str2num)
return df.join(rt_df[cols].add_suffix(f'_{self.RT}'), how='left') | Describe representative values.
Args:
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
with_rt (bool): whether show the history of Rt values
Returns:
pandas.DataFrame:
Index
str: scenario name
Columns
- max(Infected): max value of Infected
- argmax(Infected): the date when Infected shows max value
- Confirmed({date}): Confirmed on the next date of the last phase
- Infected({date}): Infected on the next date of the last phase
- Fatal({date}): Fatal on the next date of the last phase
- nth_Rt etc.: Rt value if the values are not the same values | covsirphy/analysis/scenario.py | describe | fadelrahman31/modified-covsirphhy | 0 | python | def describe(self, y0_dict=None, with_rt=True):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n with_rt (bool): whether show the history of Rt values\n\n Returns:\n pandas.DataFrame:\n Index\n str: scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n - nth_Rt etc.: Rt value if the values are not the same values\n '
df = self._describe(y0_dict=y0_dict)
if ((not with_rt) or (len(self._tracker_dict) == 1)):
return df
rt_df = self.summary().reset_index()
rt_df = rt_df.pivot_table(index=self.SERIES, columns=self.PHASE, values=self.RT)
rt_df = rt_df.fillna(self.UNKNOWN)
rt_df = rt_df.loc[(:, (rt_df.nunique() > 1))]
cols = sorted(rt_df, key=self.str2num)
return df.join(rt_df[cols].add_suffix(f'_{self.RT}'), how='left') | def describe(self, y0_dict=None, with_rt=True):
'\n Describe representative values.\n\n Args:\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n with_rt (bool): whether show the history of Rt values\n\n Returns:\n pandas.DataFrame:\n Index\n str: scenario name\n Columns\n - max(Infected): max value of Infected\n - argmax(Infected): the date when Infected shows max value\n - Confirmed({date}): Confirmed on the next date of the last phase\n - Infected({date}): Infected on the next date of the last phase\n - Fatal({date}): Fatal on the next date of the last phase\n - nth_Rt etc.: Rt value if the values are not the same values\n '
df = self._describe(y0_dict=y0_dict)
if ((not with_rt) or (len(self._tracker_dict) == 1)):
return df
rt_df = self.summary().reset_index()
rt_df = rt_df.pivot_table(index=self.SERIES, columns=self.PHASE, values=self.RT)
rt_df = rt_df.fillna(self.UNKNOWN)
rt_df = rt_df.loc[(:, (rt_df.nunique() > 1))]
cols = sorted(rt_df, key=self.str2num)
return df.join(rt_df[cols].add_suffix(f'_{self.RT}'), how='left')<|docstring|>Describe representative values.
Args:
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
with_rt (bool): whether show the history of Rt values
Returns:
pandas.DataFrame:
Index
str: scenario name
Columns
- max(Infected): max value of Infected
- argmax(Infected): the date when Infected shows max value
- Confirmed({date}): Confirmed on the next date of the last phase
- Infected({date}): Infected on the next date of the last phase
- Fatal({date}): Fatal on the next date of the last phase
- nth_Rt etc.: Rt value if the values are not the same values<|endoftext|> |
f1d0d73db85f19d8027086caf65476c774e84029c8364d7b1a51e9caebbfc6ad | def _track_param(self, name):
'\n Get the history of parameters for the scenario.\n\n Args:\n name (str): phase series name\n\n Returns:\n pandas.DataFrame:\n Index Date (pandas.TimeStamp)\n Columns\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
df = self.summary(name=name).replace(self.UNKNOWN, None)
df[self.START] = pd.to_datetime(df[self.START])
df[self.END] = pd.to_datetime(df[self.END])
df[self.DATE] = df[[self.START, self.END]].apply((lambda x: pd.date_range(x[0], x[1]).tolist()), axis=1)
df = df.reset_index(drop=True).explode(self.DATE)
df = df.drop([self.TENSE, self.START, self.END, self.ODE, self.TAU, *Evaluator.metrics(), self.TRIALS, self.RUNTIME], axis=1, errors='ignore')
df = df.set_index(self.DATE)
for col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
df[self.N] = df[self.N].astype(np.int64)
return df | Get the history of parameters for the scenario.
Args:
name (str): phase series name
Returns:
pandas.DataFrame:
Index Date (pandas.TimeStamp)
Columns
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float) | covsirphy/analysis/scenario.py | _track_param | fadelrahman31/modified-covsirphhy | 0 | python | def _track_param(self, name):
'\n Get the history of parameters for the scenario.\n\n Args:\n name (str): phase series name\n\n Returns:\n pandas.DataFrame:\n Index Date (pandas.TimeStamp)\n Columns\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
df = self.summary(name=name).replace(self.UNKNOWN, None)
df[self.START] = pd.to_datetime(df[self.START])
df[self.END] = pd.to_datetime(df[self.END])
df[self.DATE] = df[[self.START, self.END]].apply((lambda x: pd.date_range(x[0], x[1]).tolist()), axis=1)
df = df.reset_index(drop=True).explode(self.DATE)
df = df.drop([self.TENSE, self.START, self.END, self.ODE, self.TAU, *Evaluator.metrics(), self.TRIALS, self.RUNTIME], axis=1, errors='ignore')
df = df.set_index(self.DATE)
for col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
df[self.N] = df[self.N].astype(np.int64)
return df | def _track_param(self, name):
'\n Get the history of parameters for the scenario.\n\n Args:\n name (str): phase series name\n\n Returns:\n pandas.DataFrame:\n Index Date (pandas.TimeStamp)\n Columns\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
df = self.summary(name=name).replace(self.UNKNOWN, None)
df[self.START] = pd.to_datetime(df[self.START])
df[self.END] = pd.to_datetime(df[self.END])
df[self.DATE] = df[[self.START, self.END]].apply((lambda x: pd.date_range(x[0], x[1]).tolist()), axis=1)
df = df.reset_index(drop=True).explode(self.DATE)
df = df.drop([self.TENSE, self.START, self.END, self.ODE, self.TAU, *Evaluator.metrics(), self.TRIALS, self.RUNTIME], axis=1, errors='ignore')
df = df.set_index(self.DATE)
for col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
df[self.N] = df[self.N].astype(np.int64)
return df<|docstring|>Get the history of parameters for the scenario.
Args:
name (str): phase series name
Returns:
pandas.DataFrame:
Index Date (pandas.TimeStamp)
Columns
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float)<|endoftext|> |
cb090be6240ba0db6458c7cbd7aedeeea147c8ce555367ecb42ec9fa5ad73571 | def _track(self, phases=None, name='Main', y0_dict=None):
'\n Show values of parameters and variables in one dataframe for the scenario.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame:\n Index reset index\n Columns\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
sim_df = self.simulate(phases=phases, name=name, y0_dict=y0_dict, show_figure=False)
param_df = self._track_param(name=name)
return pd.merge(sim_df, param_df, how='inner', left_on=self.DATE, right_index=True, sort=True) | Show values of parameters and variables in one dataframe for the scenario.
Args:
phases (list[str] or None): phases to shoe or None (all phases)
name (str): phase series name
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame:
Index reset index
Columns
- Date (pandas.TimeStamp)
- variables (int)
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float) | covsirphy/analysis/scenario.py | _track | fadelrahman31/modified-covsirphhy | 0 | python | def _track(self, phases=None, name='Main', y0_dict=None):
'\n Show values of parameters and variables in one dataframe for the scenario.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame:\n Index reset index\n Columns\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
sim_df = self.simulate(phases=phases, name=name, y0_dict=y0_dict, show_figure=False)
param_df = self._track_param(name=name)
return pd.merge(sim_df, param_df, how='inner', left_on=self.DATE, right_index=True, sort=True) | def _track(self, phases=None, name='Main', y0_dict=None):
'\n Show values of parameters and variables in one dataframe for the scenario.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n name (str): phase series name\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame:\n Index reset index\n Columns\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
sim_df = self.simulate(phases=phases, name=name, y0_dict=y0_dict, show_figure=False)
param_df = self._track_param(name=name)
return pd.merge(sim_df, param_df, how='inner', left_on=self.DATE, right_index=True, sort=True)<|docstring|>Show values of parameters and variables in one dataframe for the scenario.
Args:
phases (list[str] or None): phases to shoe or None (all phases)
name (str): phase series name
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame:
Index reset index
Columns
- Date (pandas.TimeStamp)
- variables (int)
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float)<|endoftext|> |
b23cf701d74743eaf19ce0d4cc47a0b585fada602e0255b4d73f058c0e9fc77e | def track(self, phases=None, with_actual=True, y0_dict=None):
'\n Show values of parameters and variables in one dataframe.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True, show actual number of cases will included as "Actual" scenario\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame: tracking records\n Index\n reset index\n Columns\n - Scenario (str)\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
dataframes = []
append = dataframes.append
for name in self._tracker_dict.keys():
df = self._track(phases=phases, name=name, y0_dict=y0_dict)
df.insert(0, self.SERIES, name)
append(df)
if with_actual:
df = self._data.records(extras=False)
df.insert(0, self.SERIES, self.ACTUAL)
append(df)
return pd.concat(dataframes, axis=0, sort=False) | Show values of parameters and variables in one dataframe.
Args:
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True, show actual number of cases will included as "Actual" scenario
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame: tracking records
Index
reset index
Columns
- Scenario (str)
- Date (pandas.TimeStamp)
- variables (int)
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float) | covsirphy/analysis/scenario.py | track | fadelrahman31/modified-covsirphhy | 0 | python | def track(self, phases=None, with_actual=True, y0_dict=None):
'\n Show values of parameters and variables in one dataframe.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True, show actual number of cases will included as "Actual" scenario\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame: tracking records\n Index\n reset index\n Columns\n - Scenario (str)\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
dataframes = []
append = dataframes.append
for name in self._tracker_dict.keys():
df = self._track(phases=phases, name=name, y0_dict=y0_dict)
df.insert(0, self.SERIES, name)
append(df)
if with_actual:
df = self._data.records(extras=False)
df.insert(0, self.SERIES, self.ACTUAL)
append(df)
return pd.concat(dataframes, axis=0, sort=False) | def track(self, phases=None, with_actual=True, y0_dict=None):
'\n Show values of parameters and variables in one dataframe.\n\n Args:\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True, show actual number of cases will included as "Actual" scenario\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame: tracking records\n Index\n reset index\n Columns\n - Scenario (str)\n - Date (pandas.TimeStamp)\n - variables (int)\n - Population (int)\n - Rt (float)\n - parameter values (float)\n - day parameter values (float)\n '
dataframes = []
append = dataframes.append
for name in self._tracker_dict.keys():
df = self._track(phases=phases, name=name, y0_dict=y0_dict)
df.insert(0, self.SERIES, name)
append(df)
if with_actual:
df = self._data.records(extras=False)
df.insert(0, self.SERIES, self.ACTUAL)
append(df)
return pd.concat(dataframes, axis=0, sort=False)<|docstring|>Show values of parameters and variables in one dataframe.
Args:
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True, show actual number of cases will included as "Actual" scenario
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame: tracking records
Index
reset index
Columns
- Scenario (str)
- Date (pandas.TimeStamp)
- variables (int)
- Population (int)
- Rt (float)
- parameter values (float)
- day parameter values (float)<|endoftext|> |
567f1feaf4363cc498788ddc9e014386f5945365c5d85df121443b54cca16b95 | def _history(self, target, phases=None, with_actual=True, y0_dict=None):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n '
with_actual = (with_actual and (target in self.VALUE_COLUMNS))
df = self.track(phases=phases, with_actual=with_actual, y0_dict=y0_dict)
if (target not in df.columns):
col_str = ', '.join(list(df.columns))
raise KeyError(f'@target must be selected from {col_str}, but {target} was applied.')
return df.pivot_table(values=target, index=self.DATE, columns=self.SERIES, aggfunc='last') | Show the history of variables and parameter values to compare scenarios.
Args:
target (str): parameter or variable name to show (Rt, Infected etc.)
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True and @target is a variable name, show actual number of cases
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame | covsirphy/analysis/scenario.py | _history | fadelrahman31/modified-covsirphhy | 0 | python | def _history(self, target, phases=None, with_actual=True, y0_dict=None):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n '
with_actual = (with_actual and (target in self.VALUE_COLUMNS))
df = self.track(phases=phases, with_actual=with_actual, y0_dict=y0_dict)
if (target not in df.columns):
col_str = ', '.join(list(df.columns))
raise KeyError(f'@target must be selected from {col_str}, but {target} was applied.')
return df.pivot_table(values=target, index=self.DATE, columns=self.SERIES, aggfunc='last') | def _history(self, target, phases=None, with_actual=True, y0_dict=None):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n\n Returns:\n pandas.DataFrame\n '
with_actual = (with_actual and (target in self.VALUE_COLUMNS))
df = self.track(phases=phases, with_actual=with_actual, y0_dict=y0_dict)
if (target not in df.columns):
col_str = ', '.join(list(df.columns))
raise KeyError(f'@target must be selected from {col_str}, but {target} was applied.')
return df.pivot_table(values=target, index=self.DATE, columns=self.SERIES, aggfunc='last')<|docstring|>Show the history of variables and parameter values to compare scenarios.
Args:
target (str): parameter or variable name to show (Rt, Infected etc.)
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True and @target is a variable name, show actual number of cases
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
Returns:
pandas.DataFrame<|endoftext|> |
965b478cbc5f9f3360df44d4ce397d9f53111e7d7575d2991f6c72098089b327 | def history(self, target, phases=None, with_actual=True, y0_dict=None, **kwargs):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._history(target=target, phases=phases, with_actual=with_actual, y0_dict=y0_dict)
df.dropna(subset=[col for col in df.columns if (col != self.ACTUAL)], inplace=True)
if (target == self.RT):
ylabel = self.RT_FULL
elif (target in self.VALUE_COLUMNS):
ylabel = f'The number of {target.lower()} cases'
else:
ylabel = target
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, h=(1.0 if (target == self.RT) else None), **kwargs)
return df | Show the history of variables and parameter values to compare scenarios.
Args:
target (str): parameter or variable name to show (Rt, Infected etc.)
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True and @target is a variable name, show actual number of cases
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame | covsirphy/analysis/scenario.py | history | fadelrahman31/modified-covsirphhy | 0 | python | def history(self, target, phases=None, with_actual=True, y0_dict=None, **kwargs):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._history(target=target, phases=phases, with_actual=with_actual, y0_dict=y0_dict)
df.dropna(subset=[col for col in df.columns if (col != self.ACTUAL)], inplace=True)
if (target == self.RT):
ylabel = self.RT_FULL
elif (target in self.VALUE_COLUMNS):
ylabel = f'The number of {target.lower()} cases'
else:
ylabel = target
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, h=(1.0 if (target == self.RT) else None), **kwargs)
return df | def history(self, target, phases=None, with_actual=True, y0_dict=None, **kwargs):
'\n Show the history of variables and parameter values to compare scenarios.\n\n Args:\n target (str): parameter or variable name to show (Rt, Infected etc.)\n phases (list[str] or None): phases to shoe or None (all phases)\n with_actual (bool): if True and @target is a variable name, show actual number of cases\n y0_dict (dict or None): dictionary of initial values or None\n - key (str): variable name\n - value (float): initial value\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._history(target=target, phases=phases, with_actual=with_actual, y0_dict=y0_dict)
df.dropna(subset=[col for col in df.columns if (col != self.ACTUAL)], inplace=True)
if (target == self.RT):
ylabel = self.RT_FULL
elif (target in self.VALUE_COLUMNS):
ylabel = f'The number of {target.lower()} cases'
else:
ylabel = target
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, h=(1.0 if (target == self.RT) else None), **kwargs)
return df<|docstring|>Show the history of variables and parameter values to compare scenarios.
Args:
target (str): parameter or variable name to show (Rt, Infected etc.)
phases (list[str] or None): phases to shoe or None (all phases)
with_actual (bool): if True and @target is a variable name, show actual number of cases
y0_dict (dict or None): dictionary of initial values or None
- key (str): variable name
- value (float): initial value
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame<|endoftext|> |
79f1bba3c291f9192bc2fa9be4723de23cae1a2f814aa19184455ae453001eb6 | def history_rate(self, params=None, name='Main', **kwargs):
'\n Show change rates of parameter values in one figure.\n We can find the parameters which increased/decreased significantly.\n\n Args:\n params (list[str] or None): parameters to show\n name (str): phase series name\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._track_param(name=name)
model = self._tracker(name).last_model
cols = list((set(df.columns) & set(model.PARAMETERS)))
if (params is not None):
if (not isinstance(params, (list, set))):
raise TypeError(f'@params must be a list of parameters, but {params} were applied.')
cols = (list((set(cols) & set(params))) or cols)
df = (df.loc[(:, cols)] / df.loc[(df.index[0], cols)])
f_date = df.index[0].strftime(self.DATE_FORMAT)
title = f'{self.area}: {model.NAME} parameter change rates over time (1.0 on {f_date})'
ylabel = f'Value per that on {f_date}'
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, **kwargs)
return df | Show change rates of parameter values in one figure.
We can find the parameters which increased/decreased significantly.
Args:
params (list[str] or None): parameters to show
name (str): phase series name
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame | covsirphy/analysis/scenario.py | history_rate | fadelrahman31/modified-covsirphhy | 0 | python | def history_rate(self, params=None, name='Main', **kwargs):
'\n Show change rates of parameter values in one figure.\n We can find the parameters which increased/decreased significantly.\n\n Args:\n params (list[str] or None): parameters to show\n name (str): phase series name\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._track_param(name=name)
model = self._tracker(name).last_model
cols = list((set(df.columns) & set(model.PARAMETERS)))
if (params is not None):
if (not isinstance(params, (list, set))):
raise TypeError(f'@params must be a list of parameters, but {params} were applied.')
cols = (list((set(cols) & set(params))) or cols)
df = (df.loc[(:, cols)] / df.loc[(df.index[0], cols)])
f_date = df.index[0].strftime(self.DATE_FORMAT)
title = f'{self.area}: {model.NAME} parameter change rates over time (1.0 on {f_date})'
ylabel = f'Value per that on {f_date}'
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, **kwargs)
return df | def history_rate(self, params=None, name='Main', **kwargs):
'\n Show change rates of parameter values in one figure.\n We can find the parameters which increased/decreased significantly.\n\n Args:\n params (list[str] or None): parameters to show\n name (str): phase series name\n kwargs: the other keyword arguments of Scenario.line_plot()\n\n Returns:\n pandas.DataFrame\n '
df = self._track_param(name=name)
model = self._tracker(name).last_model
cols = list((set(df.columns) & set(model.PARAMETERS)))
if (params is not None):
if (not isinstance(params, (list, set))):
raise TypeError(f'@params must be a list of parameters, but {params} were applied.')
cols = (list((set(cols) & set(params))) or cols)
df = (df.loc[(:, cols)] / df.loc[(df.index[0], cols)])
f_date = df.index[0].strftime(self.DATE_FORMAT)
title = f'{self.area}: {model.NAME} parameter change rates over time (1.0 on {f_date})'
ylabel = f'Value per that on {f_date}'
title = f'{self.area}: {ylabel} over time'
tracker = self._tracker(self.MAIN)
self.line_plot(df=df, title=title, ylabel=ylabel, v=tracker.change_dates(), math_scale=False, **kwargs)
return df<|docstring|>Show change rates of parameter values in one figure.
We can find the parameters which increased/decreased significantly.
Args:
params (list[str] or None): parameters to show
name (str): phase series name
kwargs: the other keyword arguments of Scenario.line_plot()
Returns:
pandas.DataFrame<|endoftext|> |
732bab8eb2338e7ced2c5de3a8d69d591d7073bf6eb7c36b877233f2e35cbc66 | def retrospective(self, beginning_date, model, control='Main', target='Target', **kwargs):
'\n Perform retrospective analysis.\n Compare the actual series of phases (control) and\n series of phases with specified parameters (target).\n\n Args:\n beginning_date (str): when the parameter values start to be changed from actual values\n model (covsirphy.ModelBase): ODE model\n control (str): scenario name of control\n target (str): scenario name of target\n kwargs: keyword argument of parameter values and Estimator.run()\n\n Note:\n When parameter values are not specified,\n actual values of the last date before the beginning date will be used.\n '
param_dict = {k: v for (k, v) in kwargs.items() if (k in model.PARAMETERS)}
est_kwargs = dict((kwargs.items() - param_dict.items()))
self.clear(name=control, include_past=True)
self.trend(name=control, show_figure=False)
try:
self.separate(date=beginning_date, name=control)
except ValueError:
pass
self.estimate(model, name=control, **est_kwargs)
self.clear(name=target, include_past=False, template=control)
phases_changed = [self.num2str(i) for (i, ph) in enumerate(self._tracker(target).series) if (ph >= beginning_date)]
self.delete(phases=phases_changed, name=target)
self.add(name=target, **param_dict)
self.estimate(model, name=target, **est_kwargs) | Perform retrospective analysis.
Compare the actual series of phases (control) and
series of phases with specified parameters (target).
Args:
beginning_date (str): when the parameter values start to be changed from actual values
model (covsirphy.ModelBase): ODE model
control (str): scenario name of control
target (str): scenario name of target
kwargs: keyword argument of parameter values and Estimator.run()
Note:
When parameter values are not specified,
actual values of the last date before the beginning date will be used. | covsirphy/analysis/scenario.py | retrospective | fadelrahman31/modified-covsirphhy | 0 | python | def retrospective(self, beginning_date, model, control='Main', target='Target', **kwargs):
'\n Perform retrospective analysis.\n Compare the actual series of phases (control) and\n series of phases with specified parameters (target).\n\n Args:\n beginning_date (str): when the parameter values start to be changed from actual values\n model (covsirphy.ModelBase): ODE model\n control (str): scenario name of control\n target (str): scenario name of target\n kwargs: keyword argument of parameter values and Estimator.run()\n\n Note:\n When parameter values are not specified,\n actual values of the last date before the beginning date will be used.\n '
param_dict = {k: v for (k, v) in kwargs.items() if (k in model.PARAMETERS)}
est_kwargs = dict((kwargs.items() - param_dict.items()))
self.clear(name=control, include_past=True)
self.trend(name=control, show_figure=False)
try:
self.separate(date=beginning_date, name=control)
except ValueError:
pass
self.estimate(model, name=control, **est_kwargs)
self.clear(name=target, include_past=False, template=control)
phases_changed = [self.num2str(i) for (i, ph) in enumerate(self._tracker(target).series) if (ph >= beginning_date)]
self.delete(phases=phases_changed, name=target)
self.add(name=target, **param_dict)
self.estimate(model, name=target, **est_kwargs) | def retrospective(self, beginning_date, model, control='Main', target='Target', **kwargs):
'\n Perform retrospective analysis.\n Compare the actual series of phases (control) and\n series of phases with specified parameters (target).\n\n Args:\n beginning_date (str): when the parameter values start to be changed from actual values\n model (covsirphy.ModelBase): ODE model\n control (str): scenario name of control\n target (str): scenario name of target\n kwargs: keyword argument of parameter values and Estimator.run()\n\n Note:\n When parameter values are not specified,\n actual values of the last date before the beginning date will be used.\n '
param_dict = {k: v for (k, v) in kwargs.items() if (k in model.PARAMETERS)}
est_kwargs = dict((kwargs.items() - param_dict.items()))
self.clear(name=control, include_past=True)
self.trend(name=control, show_figure=False)
try:
self.separate(date=beginning_date, name=control)
except ValueError:
pass
self.estimate(model, name=control, **est_kwargs)
self.clear(name=target, include_past=False, template=control)
phases_changed = [self.num2str(i) for (i, ph) in enumerate(self._tracker(target).series) if (ph >= beginning_date)]
self.delete(phases=phases_changed, name=target)
self.add(name=target, **param_dict)
self.estimate(model, name=target, **est_kwargs)<|docstring|>Perform retrospective analysis.
Compare the actual series of phases (control) and
series of phases with specified parameters (target).
Args:
beginning_date (str): when the parameter values start to be changed from actual values
model (covsirphy.ModelBase): ODE model
control (str): scenario name of control
target (str): scenario name of target
kwargs: keyword argument of parameter values and Estimator.run()
Note:
When parameter values are not specified,
actual values of the last date before the beginning date will be used.<|endoftext|> |
885c10871e8eced168b5f43a4fafff615a0797184d8123434fc716b79987ac51 | def score(self, variables=None, phases=None, past_days=None, name='Main', y0_dict=None, **kwargs):
'\n Evaluate accuracy of phase setting and parameter estimation of all enabled phases all some past days.\n\n Args:\n variables (list[str] or None): variables to use in calculation\n phases (list[str] or None): phases to use in calculation\n past_days (int or None): how many past days to use in calculation, natural integer\n name(str): phase series name. If \'Main\', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: keyword arguments of covsirphy.Evaluator.score()\n\n Returns:\n float: score with the specified metrics (covsirphy.Evaluator.score())\n\n Note:\n If @variables is None, ["Infected", "Fatal", "Recovered"] will be used.\n "Confirmed", "Infected", "Fatal" and "Recovered" can be used in @variables.\n If @phases is None, all phases will be used.\n @phases and @past_days can not be specified at the same time.\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metrics.\n '
tracker = self._tracker(name)
if (past_days is not None):
if (phases is not None):
raise ValueError('@phases and @past_days cannot be specified at the same time.')
past_days = self._ensure_natural_int(past_days, name='past_days')
beginning_date = self.date_change(self._data.last_date, days=(0 - past_days))
try:
tracker.separate(date=beginning_date)
except ValueError:
pass
phases = [self.num2str(num) for (num, unit) in enumerate(tracker.series) if (unit >= beginning_date)]
return tracker.score(variables=variables, phases=phases, y0_dict=y0_dict, **kwargs) | Evaluate accuracy of phase setting and parameter estimation of all enabled phases all some past days.
Args:
variables (list[str] or None): variables to use in calculation
phases (list[str] or None): phases to use in calculation
past_days (int or None): how many past days to use in calculation, natural integer
name(str): phase series name. If 'Main', main PhaseSeries will be used
y0_dict(dict[str, float] or None): dictionary of initial values of variables
kwargs: keyword arguments of covsirphy.Evaluator.score()
Returns:
float: score with the specified metrics (covsirphy.Evaluator.score())
Note:
If @variables is None, ["Infected", "Fatal", "Recovered"] will be used.
"Confirmed", "Infected", "Fatal" and "Recovered" can be used in @variables.
If @phases is None, all phases will be used.
@phases and @past_days can not be specified at the same time.
Note:
Please refer to covsirphy.Evaluator.score() for metrics. | covsirphy/analysis/scenario.py | score | fadelrahman31/modified-covsirphhy | 0 | python | def score(self, variables=None, phases=None, past_days=None, name='Main', y0_dict=None, **kwargs):
'\n Evaluate accuracy of phase setting and parameter estimation of all enabled phases all some past days.\n\n Args:\n variables (list[str] or None): variables to use in calculation\n phases (list[str] or None): phases to use in calculation\n past_days (int or None): how many past days to use in calculation, natural integer\n name(str): phase series name. If \'Main\', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: keyword arguments of covsirphy.Evaluator.score()\n\n Returns:\n float: score with the specified metrics (covsirphy.Evaluator.score())\n\n Note:\n If @variables is None, ["Infected", "Fatal", "Recovered"] will be used.\n "Confirmed", "Infected", "Fatal" and "Recovered" can be used in @variables.\n If @phases is None, all phases will be used.\n @phases and @past_days can not be specified at the same time.\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metrics.\n '
tracker = self._tracker(name)
if (past_days is not None):
if (phases is not None):
raise ValueError('@phases and @past_days cannot be specified at the same time.')
past_days = self._ensure_natural_int(past_days, name='past_days')
beginning_date = self.date_change(self._data.last_date, days=(0 - past_days))
try:
tracker.separate(date=beginning_date)
except ValueError:
pass
phases = [self.num2str(num) for (num, unit) in enumerate(tracker.series) if (unit >= beginning_date)]
return tracker.score(variables=variables, phases=phases, y0_dict=y0_dict, **kwargs) | def score(self, variables=None, phases=None, past_days=None, name='Main', y0_dict=None, **kwargs):
'\n Evaluate accuracy of phase setting and parameter estimation of all enabled phases all some past days.\n\n Args:\n variables (list[str] or None): variables to use in calculation\n phases (list[str] or None): phases to use in calculation\n past_days (int or None): how many past days to use in calculation, natural integer\n name(str): phase series name. If \'Main\', main PhaseSeries will be used\n y0_dict(dict[str, float] or None): dictionary of initial values of variables\n kwargs: keyword arguments of covsirphy.Evaluator.score()\n\n Returns:\n float: score with the specified metrics (covsirphy.Evaluator.score())\n\n Note:\n If @variables is None, ["Infected", "Fatal", "Recovered"] will be used.\n "Confirmed", "Infected", "Fatal" and "Recovered" can be used in @variables.\n If @phases is None, all phases will be used.\n @phases and @past_days can not be specified at the same time.\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metrics.\n '
tracker = self._tracker(name)
if (past_days is not None):
if (phases is not None):
raise ValueError('@phases and @past_days cannot be specified at the same time.')
past_days = self._ensure_natural_int(past_days, name='past_days')
beginning_date = self.date_change(self._data.last_date, days=(0 - past_days))
try:
tracker.separate(date=beginning_date)
except ValueError:
pass
phases = [self.num2str(num) for (num, unit) in enumerate(tracker.series) if (unit >= beginning_date)]
return tracker.score(variables=variables, phases=phases, y0_dict=y0_dict, **kwargs)<|docstring|>Evaluate accuracy of phase setting and parameter estimation of all enabled phases all some past days.
Args:
variables (list[str] or None): variables to use in calculation
phases (list[str] or None): phases to use in calculation
past_days (int or None): how many past days to use in calculation, natural integer
name(str): phase series name. If 'Main', main PhaseSeries will be used
y0_dict(dict[str, float] or None): dictionary of initial values of variables
kwargs: keyword arguments of covsirphy.Evaluator.score()
Returns:
float: score with the specified metrics (covsirphy.Evaluator.score())
Note:
If @variables is None, ["Infected", "Fatal", "Recovered"] will be used.
"Confirmed", "Infected", "Fatal" and "Recovered" can be used in @variables.
If @phases is None, all phases will be used.
@phases and @past_days can not be specified at the same time.
Note:
Please refer to covsirphy.Evaluator.score() for metrics.<|endoftext|> |
580fbe216fb4f97fd3104c6363003333b84f47b5a106a0da68554fcec1686201 | def estimate_delay(self, oxcgrt_data=None, indicator='Stringency_index', target='Confirmed', percentile=25, limits=(7, 30), **kwargs):
'\n Estimate delay period [days], assuming the indicator impact on the target value with delay.\n The average of representative value (percentile) and @min_size will be returned.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset\n indicator (str): indicator name, a column of any registered datasets\n target (str): target name, a column of any registered datasets\n percentile (int): percentile to calculate the representative value, in (0, 100)\n limits (tuple(int, int)): minimum/maximum size of the delay period [days]\n kwargs: keyword arguments of DataHandler.estimate_delay()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n UserWarning: failed in calculating and returned the default value (recovery period)\n\n Returns:\n tuple(int, pandas.DataFrame):\n - int: the estimated number of days of delay [day] (mode value)\n - pandas.DataFrame:\n Index\n reset index\n Columns\n - (int or float): column defined by @indicator\n - (int or float): column defined by @target\n - (int): column defined by @delay_name [days]\n\n Note:\n - Average recovered period of JHU dataset will be used as returned value when the estimated value was not in value_range.\n - @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
(min_size, max_days) = limits
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
if ('value_range' in kwargs):
warnings.warn('@value_range argument was deprecated.', DeprecationWarning, stacklevel=1)
df = self._data.estimate_delay(indicator=indicator, target=target, min_size=min_size, delay_name='Period Length', **find_args(DataHandler.estimate_delay, **kwargs))
df.dropna(subset=['Period Length'], inplace=True)
df.sort_values('Period Length', inplace=True)
df.reset_index(inplace=True, drop=True)
if (max_days is not None):
df = df[(df['Period Length'] <= max_days)]
if df.empty:
return (self._data.recovery_period(), df)
Q1 = np.percentile(df['Period Length'], percentile, interpolation='midpoint')
low_lim = min_size
delay_period = int(((low_lim + Q1) / 2))
return (int(delay_period), df) | Estimate delay period [days], assuming the indicator impact on the target value with delay.
The average of representative value (percentile) and @min_size will be returned.
Args:
oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset
indicator (str): indicator name, a column of any registered datasets
target (str): target name, a column of any registered datasets
percentile (int): percentile to calculate the representative value, in (0, 100)
limits (tuple(int, int)): minimum/maximum size of the delay period [days]
kwargs: keyword arguments of DataHandler.estimate_delay()
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
UserWarning: failed in calculating and returned the default value (recovery period)
Returns:
tuple(int, pandas.DataFrame):
- int: the estimated number of days of delay [day] (mode value)
- pandas.DataFrame:
Index
reset index
Columns
- (int or float): column defined by @indicator
- (int or float): column defined by @target
- (int): column defined by @delay_name [days]
Note:
- Average recovered period of JHU dataset will be used as returned value when the estimated value was not in value_range.
- @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]). | covsirphy/analysis/scenario.py | estimate_delay | fadelrahman31/modified-covsirphhy | 0 | python | def estimate_delay(self, oxcgrt_data=None, indicator='Stringency_index', target='Confirmed', percentile=25, limits=(7, 30), **kwargs):
'\n Estimate delay period [days], assuming the indicator impact on the target value with delay.\n The average of representative value (percentile) and @min_size will be returned.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset\n indicator (str): indicator name, a column of any registered datasets\n target (str): target name, a column of any registered datasets\n percentile (int): percentile to calculate the representative value, in (0, 100)\n limits (tuple(int, int)): minimum/maximum size of the delay period [days]\n kwargs: keyword arguments of DataHandler.estimate_delay()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n UserWarning: failed in calculating and returned the default value (recovery period)\n\n Returns:\n tuple(int, pandas.DataFrame):\n - int: the estimated number of days of delay [day] (mode value)\n - pandas.DataFrame:\n Index\n reset index\n Columns\n - (int or float): column defined by @indicator\n - (int or float): column defined by @target\n - (int): column defined by @delay_name [days]\n\n Note:\n - Average recovered period of JHU dataset will be used as returned value when the estimated value was not in value_range.\n - @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
(min_size, max_days) = limits
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
if ('value_range' in kwargs):
warnings.warn('@value_range argument was deprecated.', DeprecationWarning, stacklevel=1)
df = self._data.estimate_delay(indicator=indicator, target=target, min_size=min_size, delay_name='Period Length', **find_args(DataHandler.estimate_delay, **kwargs))
df.dropna(subset=['Period Length'], inplace=True)
df.sort_values('Period Length', inplace=True)
df.reset_index(inplace=True, drop=True)
if (max_days is not None):
df = df[(df['Period Length'] <= max_days)]
if df.empty:
return (self._data.recovery_period(), df)
Q1 = np.percentile(df['Period Length'], percentile, interpolation='midpoint')
low_lim = min_size
delay_period = int(((low_lim + Q1) / 2))
return (int(delay_period), df) | def estimate_delay(self, oxcgrt_data=None, indicator='Stringency_index', target='Confirmed', percentile=25, limits=(7, 30), **kwargs):
'\n Estimate delay period [days], assuming the indicator impact on the target value with delay.\n The average of representative value (percentile) and @min_size will be returned.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset\n indicator (str): indicator name, a column of any registered datasets\n target (str): target name, a column of any registered datasets\n percentile (int): percentile to calculate the representative value, in (0, 100)\n limits (tuple(int, int)): minimum/maximum size of the delay period [days]\n kwargs: keyword arguments of DataHandler.estimate_delay()\n\n Raises:\n NotRegisteredMainError: either JHUData or PopulationData was not registered\n SubsetNotFoundError: failed in subsetting because of lack of data\n UserWarning: failed in calculating and returned the default value (recovery period)\n\n Returns:\n tuple(int, pandas.DataFrame):\n - int: the estimated number of days of delay [day] (mode value)\n - pandas.DataFrame:\n Index\n reset index\n Columns\n - (int or float): column defined by @indicator\n - (int or float): column defined by @target\n - (int): column defined by @delay_name [days]\n\n Note:\n - Average recovered period of JHU dataset will be used as returned value when the estimated value was not in value_range.\n - @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
(min_size, max_days) = limits
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
if ('value_range' in kwargs):
warnings.warn('@value_range argument was deprecated.', DeprecationWarning, stacklevel=1)
df = self._data.estimate_delay(indicator=indicator, target=target, min_size=min_size, delay_name='Period Length', **find_args(DataHandler.estimate_delay, **kwargs))
df.dropna(subset=['Period Length'], inplace=True)
df.sort_values('Period Length', inplace=True)
df.reset_index(inplace=True, drop=True)
if (max_days is not None):
df = df[(df['Period Length'] <= max_days)]
if df.empty:
return (self._data.recovery_period(), df)
Q1 = np.percentile(df['Period Length'], percentile, interpolation='midpoint')
low_lim = min_size
delay_period = int(((low_lim + Q1) / 2))
return (int(delay_period), df)<|docstring|>Estimate delay period [days], assuming the indicator impact on the target value with delay.
The average of representative value (percentile) and @min_size will be returned.
Args:
oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset
indicator (str): indicator name, a column of any registered datasets
target (str): target name, a column of any registered datasets
percentile (int): percentile to calculate the representative value, in (0, 100)
limits (tuple(int, int)): minimum/maximum size of the delay period [days]
kwargs: keyword arguments of DataHandler.estimate_delay()
Raises:
NotRegisteredMainError: either JHUData or PopulationData was not registered
SubsetNotFoundError: failed in subsetting because of lack of data
UserWarning: failed in calculating and returned the default value (recovery period)
Returns:
tuple(int, pandas.DataFrame):
- int: the estimated number of days of delay [day] (mode value)
- pandas.DataFrame:
Index
reset index
Columns
- (int or float): column defined by @indicator
- (int or float): column defined by @target
- (int): column defined by @delay_name [days]
Note:
- Average recovered period of JHU dataset will be used as returned value when the estimated value was not in value_range.
- @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).<|endoftext|> |
433b9ea41e1510e3316cccc4f0e91b11d5e6f44000cb8d08919963bb050bac47 | def fit(self, oxcgrt_data=None, name='Main', delay=None, removed_cols=None, metric=None, metrics='R2', **kwargs):
'\n Fit regressors to predict the parameter values in the future phases,\n assuming that indicators will impact on ODE parameter values/the number of cases with delay.\n Please refer to covsirphy.RegressionHander class.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset, deprecated\n name (str): scenario name\n test_size (float): proportion of the test dataset of Elastic Net regression\n seed (int): random seed when spliting the dataset to train/test data\n delay (int or None): delay period [days] or None (Scenario.estimate_delay() calculate automatically)\n removed_cols (list[str] or None): list of variables to remove from X dataset or None (indicators used to estimate delay period)\n metric (str or None): metric name or None (use @metrics)\n metrics (str): alias of @metric\n kwargs: keyword arguments of sklearn.model_selection.train_test_split(test_size=0.2, random_state=0)\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n\n Returns:\n dict: this is the same as covsirphy.Regressionhander.to_dict()\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metric names.\n\n Note:\n If @seed is included in kwargs, this will be converted to @random_state.\n '
metric = (metric or metrics)
self.clear(name=name, include_past=False)
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
model = self._tracker(name).last_model
if (model is None):
raise UnExecutedError('Scenario.estimate() or Scenario.add()', message=f", specifying @model (covsirphy.SIRF etc.) and @name='{name}'.")
if (delay is None):
(delay, delay_df) = self.estimate_delay(oxcgrt_data)
removed_cols = list((set(delay_df.columns.tolist()) | set((removed_cols or []))))
else:
delay = self._ensure_natural_int(delay, name='delay')
removed_cols = (removed_cols or None)
param_df = self._track_param(name=name)[model.PARAMETERS]
try:
records_df = self._data.records(main=True, extras=True).set_index(self.DATE)
except NotRegisteredExtraError:
raise NotRegisteredExtraError('Scenario.register(jhu_data, population_data, extras=[...])', message='with extra datasets') from None
records_df = records_df.loc[(:, (~ records_df.columns.isin(removed_cols)))]
data = param_df.join(records_df)
handler = RegressionHandler(data=data, model=model, delay=delay, **kwargs)
handler.fit(metric=metric)
self._reghandler_dict[name] = handler
return handler.to_dict(metric=metric) | Fit regressors to predict the parameter values in the future phases,
assuming that indicators will impact on ODE parameter values/the number of cases with delay.
Please refer to covsirphy.RegressionHander class.
Args:
oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset, deprecated
name (str): scenario name
test_size (float): proportion of the test dataset of Elastic Net regression
seed (int): random seed when spliting the dataset to train/test data
delay (int or None): delay period [days] or None (Scenario.estimate_delay() calculate automatically)
removed_cols (list[str] or None): list of variables to remove from X dataset or None (indicators used to estimate delay period)
metric (str or None): metric name or None (use @metrics)
metrics (str): alias of @metric
kwargs: keyword arguments of sklearn.model_selection.train_test_split(test_size=0.2, random_state=0)
Raises:
covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed
Returns:
dict: this is the same as covsirphy.Regressionhander.to_dict()
Note:
@oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).
Note:
Please refer to covsirphy.Evaluator.score() for metric names.
Note:
If @seed is included in kwargs, this will be converted to @random_state. | covsirphy/analysis/scenario.py | fit | fadelrahman31/modified-covsirphhy | 0 | python | def fit(self, oxcgrt_data=None, name='Main', delay=None, removed_cols=None, metric=None, metrics='R2', **kwargs):
'\n Fit regressors to predict the parameter values in the future phases,\n assuming that indicators will impact on ODE parameter values/the number of cases with delay.\n Please refer to covsirphy.RegressionHander class.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset, deprecated\n name (str): scenario name\n test_size (float): proportion of the test dataset of Elastic Net regression\n seed (int): random seed when spliting the dataset to train/test data\n delay (int or None): delay period [days] or None (Scenario.estimate_delay() calculate automatically)\n removed_cols (list[str] or None): list of variables to remove from X dataset or None (indicators used to estimate delay period)\n metric (str or None): metric name or None (use @metrics)\n metrics (str): alias of @metric\n kwargs: keyword arguments of sklearn.model_selection.train_test_split(test_size=0.2, random_state=0)\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n\n Returns:\n dict: this is the same as covsirphy.Regressionhander.to_dict()\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metric names.\n\n Note:\n If @seed is included in kwargs, this will be converted to @random_state.\n '
metric = (metric or metrics)
self.clear(name=name, include_past=False)
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
model = self._tracker(name).last_model
if (model is None):
raise UnExecutedError('Scenario.estimate() or Scenario.add()', message=f", specifying @model (covsirphy.SIRF etc.) and @name='{name}'.")
if (delay is None):
(delay, delay_df) = self.estimate_delay(oxcgrt_data)
removed_cols = list((set(delay_df.columns.tolist()) | set((removed_cols or []))))
else:
delay = self._ensure_natural_int(delay, name='delay')
removed_cols = (removed_cols or None)
param_df = self._track_param(name=name)[model.PARAMETERS]
try:
records_df = self._data.records(main=True, extras=True).set_index(self.DATE)
except NotRegisteredExtraError:
raise NotRegisteredExtraError('Scenario.register(jhu_data, population_data, extras=[...])', message='with extra datasets') from None
records_df = records_df.loc[(:, (~ records_df.columns.isin(removed_cols)))]
data = param_df.join(records_df)
handler = RegressionHandler(data=data, model=model, delay=delay, **kwargs)
handler.fit(metric=metric)
self._reghandler_dict[name] = handler
return handler.to_dict(metric=metric) | def fit(self, oxcgrt_data=None, name='Main', delay=None, removed_cols=None, metric=None, metrics='R2', **kwargs):
'\n Fit regressors to predict the parameter values in the future phases,\n assuming that indicators will impact on ODE parameter values/the number of cases with delay.\n Please refer to covsirphy.RegressionHander class.\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset, deprecated\n name (str): scenario name\n test_size (float): proportion of the test dataset of Elastic Net regression\n seed (int): random seed when spliting the dataset to train/test data\n delay (int or None): delay period [days] or None (Scenario.estimate_delay() calculate automatically)\n removed_cols (list[str] or None): list of variables to remove from X dataset or None (indicators used to estimate delay period)\n metric (str or None): metric name or None (use @metrics)\n metrics (str): alias of @metric\n kwargs: keyword arguments of sklearn.model_selection.train_test_split(test_size=0.2, random_state=0)\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n\n Returns:\n dict: this is the same as covsirphy.Regressionhander.to_dict()\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metric names.\n\n Note:\n If @seed is included in kwargs, this will be converted to @random_state.\n '
metric = (metric or metrics)
self.clear(name=name, include_past=False)
if (oxcgrt_data is not None):
warnings.warn('Please use Scenario.register(extras=[oxcgrt_data]) rather than Scenario.fit(oxcgrt_data).', DeprecationWarning, stacklevel=1)
self.register(extras=[oxcgrt_data])
model = self._tracker(name).last_model
if (model is None):
raise UnExecutedError('Scenario.estimate() or Scenario.add()', message=f", specifying @model (covsirphy.SIRF etc.) and @name='{name}'.")
if (delay is None):
(delay, delay_df) = self.estimate_delay(oxcgrt_data)
removed_cols = list((set(delay_df.columns.tolist()) | set((removed_cols or []))))
else:
delay = self._ensure_natural_int(delay, name='delay')
removed_cols = (removed_cols or None)
param_df = self._track_param(name=name)[model.PARAMETERS]
try:
records_df = self._data.records(main=True, extras=True).set_index(self.DATE)
except NotRegisteredExtraError:
raise NotRegisteredExtraError('Scenario.register(jhu_data, population_data, extras=[...])', message='with extra datasets') from None
records_df = records_df.loc[(:, (~ records_df.columns.isin(removed_cols)))]
data = param_df.join(records_df)
handler = RegressionHandler(data=data, model=model, delay=delay, **kwargs)
handler.fit(metric=metric)
self._reghandler_dict[name] = handler
return handler.to_dict(metric=metric)<|docstring|>Fit regressors to predict the parameter values in the future phases,
assuming that indicators will impact on ODE parameter values/the number of cases with delay.
Please refer to covsirphy.RegressionHander class.
Args:
oxcgrt_data (covsirphy.OxCGRTData): OxCGRT dataset, deprecated
name (str): scenario name
test_size (float): proportion of the test dataset of Elastic Net regression
seed (int): random seed when spliting the dataset to train/test data
delay (int or None): delay period [days] or None (Scenario.estimate_delay() calculate automatically)
removed_cols (list[str] or None): list of variables to remove from X dataset or None (indicators used to estimate delay period)
metric (str or None): metric name or None (use @metrics)
metrics (str): alias of @metric
kwargs: keyword arguments of sklearn.model_selection.train_test_split(test_size=0.2, random_state=0)
Raises:
covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed
Returns:
dict: this is the same as covsirphy.Regressionhander.to_dict()
Note:
@oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).
Note:
Please refer to covsirphy.Evaluator.score() for metric names.
Note:
If @seed is included in kwargs, this will be converted to @random_state.<|endoftext|> |
154591b733000909c32ce3f9136ea3bb2007af134dbaac11b3fd5e0df2a891a7 | def predict(self, days=None, name='Main'):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n days (list[int]): list of days to predict or None (only the max value)\n name (str): scenario name\n\n Raises:\n covsirphy.UnExecutedError: Scenario.fit() was not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n '
if (name not in self._reghandler_dict):
raise UnExecutedError(f'Scenario.fit(name={name})')
handler = self._reghandler_dict[name]
df = handler.predict()
df.index = [date.strftime(self.DATE_FORMAT) for date in df.index]
df.index.name = 'end_date'
days = (days or [(len(df) - 1)])
self._ensure_list(days, candidates=list(range(len(df))), name='days')
phase_df = df.reset_index().loc[(days, :)]
for phase_dict in phase_df.to_dict(orient='records'):
self.add(name=name, **phase_dict)
return self | Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,
assuming that OxCGRT scores will impact on ODE parameter values with delay.
New future phases will be added (over-written).
Args:
days (list[int]): list of days to predict or None (only the max value)
name (str): scenario name
Raises:
covsirphy.UnExecutedError: Scenario.fit() was not performed
NotRegisteredExtraError: no extra datasets were registered
Returns:
covsirphy.Scenario: self | covsirphy/analysis/scenario.py | predict | fadelrahman31/modified-covsirphhy | 0 | python | def predict(self, days=None, name='Main'):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n days (list[int]): list of days to predict or None (only the max value)\n name (str): scenario name\n\n Raises:\n covsirphy.UnExecutedError: Scenario.fit() was not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n '
if (name not in self._reghandler_dict):
raise UnExecutedError(f'Scenario.fit(name={name})')
handler = self._reghandler_dict[name]
df = handler.predict()
df.index = [date.strftime(self.DATE_FORMAT) for date in df.index]
df.index.name = 'end_date'
days = (days or [(len(df) - 1)])
self._ensure_list(days, candidates=list(range(len(df))), name='days')
phase_df = df.reset_index().loc[(days, :)]
for phase_dict in phase_df.to_dict(orient='records'):
self.add(name=name, **phase_dict)
return self | def predict(self, days=None, name='Main'):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n days (list[int]): list of days to predict or None (only the max value)\n name (str): scenario name\n\n Raises:\n covsirphy.UnExecutedError: Scenario.fit() was not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n '
if (name not in self._reghandler_dict):
raise UnExecutedError(f'Scenario.fit(name={name})')
handler = self._reghandler_dict[name]
df = handler.predict()
df.index = [date.strftime(self.DATE_FORMAT) for date in df.index]
df.index.name = 'end_date'
days = (days or [(len(df) - 1)])
self._ensure_list(days, candidates=list(range(len(df))), name='days')
phase_df = df.reset_index().loc[(days, :)]
for phase_dict in phase_df.to_dict(orient='records'):
self.add(name=name, **phase_dict)
return self<|docstring|>Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,
assuming that OxCGRT scores will impact on ODE parameter values with delay.
New future phases will be added (over-written).
Args:
days (list[int]): list of days to predict or None (only the max value)
name (str): scenario name
Raises:
covsirphy.UnExecutedError: Scenario.fit() was not performed
NotRegisteredExtraError: no extra datasets were registered
Returns:
covsirphy.Scenario: self<|endoftext|> |
cae5ff0288937b54ae3815f8039457ad0109cd514fe1045be0e5b76aa9787ec0 | def fit_predict(self, oxcgrt_data=None, name='Main', **kwargs):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData or None): OxCGRT dataset\n name (str): scenario name\n kwargs: the other arguments of Scenario.fit() and Scenario.predict()\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
self.fit(oxcgrt_data=oxcgrt_data, name=name, **find_args(Scenario.fit, **kwargs))
self.predict(name=name, **find_args(Scenario.predict, **kwargs))
return self | Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,
assuming that OxCGRT scores will impact on ODE parameter values with delay.
New future phases will be added (over-written).
Args:
oxcgrt_data (covsirphy.OxCGRTData or None): OxCGRT dataset
name (str): scenario name
kwargs: the other arguments of Scenario.fit() and Scenario.predict()
Raises:
covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed
NotRegisteredExtraError: no extra datasets were registered
Returns:
covsirphy.Scenario: self
Note:
@oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]). | covsirphy/analysis/scenario.py | fit_predict | fadelrahman31/modified-covsirphhy | 0 | python | def fit_predict(self, oxcgrt_data=None, name='Main', **kwargs):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData or None): OxCGRT dataset\n name (str): scenario name\n kwargs: the other arguments of Scenario.fit() and Scenario.predict()\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
self.fit(oxcgrt_data=oxcgrt_data, name=name, **find_args(Scenario.fit, **kwargs))
self.predict(name=name, **find_args(Scenario.predict, **kwargs))
return self | def fit_predict(self, oxcgrt_data=None, name='Main', **kwargs):
'\n Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,\n assuming that OxCGRT scores will impact on ODE parameter values with delay.\n New future phases will be added (over-written).\n\n Args:\n oxcgrt_data (covsirphy.OxCGRTData or None): OxCGRT dataset\n name (str): scenario name\n kwargs: the other arguments of Scenario.fit() and Scenario.predict()\n\n Raises:\n covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed\n NotRegisteredExtraError: no extra datasets were registered\n\n Returns:\n covsirphy.Scenario: self\n\n Note:\n @oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).\n '
self.fit(oxcgrt_data=oxcgrt_data, name=name, **find_args(Scenario.fit, **kwargs))
self.predict(name=name, **find_args(Scenario.predict, **kwargs))
return self<|docstring|>Predict parameter values of the future phases using Elastic Net regression with OxCGRT scores,
assuming that OxCGRT scores will impact on ODE parameter values with delay.
New future phases will be added (over-written).
Args:
oxcgrt_data (covsirphy.OxCGRTData or None): OxCGRT dataset
name (str): scenario name
kwargs: the other arguments of Scenario.fit() and Scenario.predict()
Raises:
covsirphy.UnExecutedError: Scenario.estimate() or Scenario.add() were not performed
NotRegisteredExtraError: no extra datasets were registered
Returns:
covsirphy.Scenario: self
Note:
@oxcgrt_data argument was deprecated. Please use Scenario.register(extras=[oxcgrt_data]).<|endoftext|> |
47f61888f4d7896342de44b6140d964db7b873233ccb6b9073c5d98b08cd9c65 | def out_clear(self):
'Erase terminal screen area'
tot_r = (self.rows + 2)
tot_c = (self.cols + 2)
for r in range(tot_r):
print(('\x08' * tot_c), end='')
print((' ' * (tot_c + 5)), end='')
print(('\x08' * 5), end='')
print('\x1b[A', end='')
print(('\x08' * tot_c), end='') | Erase terminal screen area | lcd_restful/fake.py | out_clear | rfarley3/lcd-restful | 0 | python | def out_clear(self):
tot_r = (self.rows + 2)
tot_c = (self.cols + 2)
for r in range(tot_r):
print(('\x08' * tot_c), end=)
print((' ' * (tot_c + 5)), end=)
print(('\x08' * 5), end=)
print('\x1b[A', end=)
print(('\x08' * tot_c), end=) | def out_clear(self):
tot_r = (self.rows + 2)
tot_c = (self.cols + 2)
for r in range(tot_r):
print(('\x08' * tot_c), end=)
print((' ' * (tot_c + 5)), end=)
print(('\x08' * 5), end=)
print('\x1b[A', end=)
print(('\x08' * tot_c), end=)<|docstring|>Erase terminal screen area<|endoftext|> |
9bbc9e6e055ea8d874385a076b5b4ec582d2e512f642b1568343b332a3d57d1e | def out_draw(self):
'Output matrix of chars to terminal screen area'
print(text_type(self)) | Output matrix of chars to terminal screen area | lcd_restful/fake.py | out_draw | rfarley3/lcd-restful | 0 | python | def out_draw(self):
print(text_type(self)) | def out_draw(self):
print(text_type(self))<|docstring|>Output matrix of chars to terminal screen area<|endoftext|> |
55e32ced5ef1d4d3a2762f12d32e8d029cb02deb973d680f89dd6ad08346ff67 | def _set(self, pin, value):
'Gpio.output/_set will call this to give HW a trigger to read'
old_val = self.pins.get(pin)
self.pins[pin] = value
if (pin == self.pin_map['en']):
if ((old_val is 0) and (value is 1)):
self.read() | Gpio.output/_set will call this to give HW a trigger to read | lcd_restful/fake.py | _set | rfarley3/lcd-restful | 0 | python | def _set(self, pin, value):
old_val = self.pins.get(pin)
self.pins[pin] = value
if (pin == self.pin_map['en']):
if ((old_val is 0) and (value is 1)):
self.read() | def _set(self, pin, value):
old_val = self.pins.get(pin)
self.pins[pin] = value
if (pin == self.pin_map['en']):
if ((old_val is 0) and (value is 1)):
self.read()<|docstring|>Gpio.output/_set will call this to give HW a trigger to read<|endoftext|> |
a849c2ba3c77b3e072a02372031414a7d0b462b2896c936864f2be1e3d3e7c88 | def write4(self, half_word):
'We get 4b at a time, combine each pair for 8b'
if self.write4_1:
self.upper = (half_word << 4)
self.write4_1 = False
return
full_word = (self.upper | half_word)
self.write4_1 = True
self.upper = None
self.write8(full_word) | We get 4b at a time, combine each pair for 8b | lcd_restful/fake.py | write4 | rfarley3/lcd-restful | 0 | python | def write4(self, half_word):
if self.write4_1:
self.upper = (half_word << 4)
self.write4_1 = False
return
full_word = (self.upper | half_word)
self.write4_1 = True
self.upper = None
self.write8(full_word) | def write4(self, half_word):
if self.write4_1:
self.upper = (half_word << 4)
self.write4_1 = False
return
full_word = (self.upper | half_word)
self.write4_1 = True
self.upper = None
self.write8(full_word)<|docstring|>We get 4b at a time, combine each pair for 8b<|endoftext|> |
ad165707304d82255f2ee7be79f2629efd68dfad2de8287a2358c37da4b48d86 | def close_pop_up_then(self, callback):
'Close popup then execute callback'
def fn(*args, **kwargs):
self.close_pop_up()
callback()
return fn | Close popup then execute callback | mitzasql/ui/widgets/session_popup_launcher.py | close_pop_up_then | oliverseal/mitzasql | 0 | python | def close_pop_up_then(self, callback):
def fn(*args, **kwargs):
self.close_pop_up()
callback()
return fn | def close_pop_up_then(self, callback):
def fn(*args, **kwargs):
self.close_pop_up()
callback()
return fn<|docstring|>Close popup then execute callback<|endoftext|> |
f0176f16e1dbe71a166a2f94fa4a05723cc43333ea90dbf4d4bd43ffb5899c19 | def generate_increasing_rows(previous_row: List, min_value: int, max_value: int, max_vector_size: int, recursive_step: int=0, row_list: List=None) -> List[int]:
'\n A generator which builds are possible vectors of a certain size (max_vector_size) that are increasing, where its\n entries are taken from a range (the discrete interval [min_value, max_value]).\n\n Args:\n min_value: An integer, representing the minimum value of the entries of the vector.\n max_value: An integer, representing the maximum value of the entries of the vector.\n max_vector_size: An integer, representing the size of the vector to be generated.\n recursive_step: An integer, representing the number of recursive calls. It is used as the stop criteria.\n row_list: A list of integers, representing the generated vector.\n\n Returns:\n A list of integers, representing the vector with size max_vector_size and which entries are in increasing order.\n '
if (row_list is None):
row_list = []
if (recursive_step == max_vector_size):
(yield row_list)
else:
minimum_row_value = min_value
if (len(previous_row) > 0):
minimum_row_value = max(min_value, previous_row[(recursive_step + 1)])
for i in range(minimum_row_value, (max_value + 1)):
new_row = row_list.copy()
new_row.append(i)
(yield from generate_increasing_rows(previous_row=previous_row, min_value=i, max_value=max_value, max_vector_size=max_vector_size, recursive_step=(recursive_step + 1), row_list=new_row)) | A generator which builds are possible vectors of a certain size (max_vector_size) that are increasing, where its
entries are taken from a range (the discrete interval [min_value, max_value]).
Args:
min_value: An integer, representing the minimum value of the entries of the vector.
max_value: An integer, representing the maximum value of the entries of the vector.
max_vector_size: An integer, representing the size of the vector to be generated.
recursive_step: An integer, representing the number of recursive calls. It is used as the stop criteria.
row_list: A list of integers, representing the generated vector.
Returns:
A list of integers, representing the vector with size max_vector_size and which entries are in increasing order. | discrete_fuzzy_operators/generators/tnorms/tnorms_iterative_generator_utils/tnorms_iterative_generator_utils.py | generate_increasing_rows | mmunar97/discrete-fuzzy-operators | 0 | python | def generate_increasing_rows(previous_row: List, min_value: int, max_value: int, max_vector_size: int, recursive_step: int=0, row_list: List=None) -> List[int]:
'\n A generator which builds are possible vectors of a certain size (max_vector_size) that are increasing, where its\n entries are taken from a range (the discrete interval [min_value, max_value]).\n\n Args:\n min_value: An integer, representing the minimum value of the entries of the vector.\n max_value: An integer, representing the maximum value of the entries of the vector.\n max_vector_size: An integer, representing the size of the vector to be generated.\n recursive_step: An integer, representing the number of recursive calls. It is used as the stop criteria.\n row_list: A list of integers, representing the generated vector.\n\n Returns:\n A list of integers, representing the vector with size max_vector_size and which entries are in increasing order.\n '
if (row_list is None):
row_list = []
if (recursive_step == max_vector_size):
(yield row_list)
else:
minimum_row_value = min_value
if (len(previous_row) > 0):
minimum_row_value = max(min_value, previous_row[(recursive_step + 1)])
for i in range(minimum_row_value, (max_value + 1)):
new_row = row_list.copy()
new_row.append(i)
(yield from generate_increasing_rows(previous_row=previous_row, min_value=i, max_value=max_value, max_vector_size=max_vector_size, recursive_step=(recursive_step + 1), row_list=new_row)) | def generate_increasing_rows(previous_row: List, min_value: int, max_value: int, max_vector_size: int, recursive_step: int=0, row_list: List=None) -> List[int]:
'\n A generator which builds are possible vectors of a certain size (max_vector_size) that are increasing, where its\n entries are taken from a range (the discrete interval [min_value, max_value]).\n\n Args:\n min_value: An integer, representing the minimum value of the entries of the vector.\n max_value: An integer, representing the maximum value of the entries of the vector.\n max_vector_size: An integer, representing the size of the vector to be generated.\n recursive_step: An integer, representing the number of recursive calls. It is used as the stop criteria.\n row_list: A list of integers, representing the generated vector.\n\n Returns:\n A list of integers, representing the vector with size max_vector_size and which entries are in increasing order.\n '
if (row_list is None):
row_list = []
if (recursive_step == max_vector_size):
(yield row_list)
else:
minimum_row_value = min_value
if (len(previous_row) > 0):
minimum_row_value = max(min_value, previous_row[(recursive_step + 1)])
for i in range(minimum_row_value, (max_value + 1)):
new_row = row_list.copy()
new_row.append(i)
(yield from generate_increasing_rows(previous_row=previous_row, min_value=i, max_value=max_value, max_vector_size=max_vector_size, recursive_step=(recursive_step + 1), row_list=new_row))<|docstring|>A generator which builds are possible vectors of a certain size (max_vector_size) that are increasing, where its
entries are taken from a range (the discrete interval [min_value, max_value]).
Args:
min_value: An integer, representing the minimum value of the entries of the vector.
max_value: An integer, representing the maximum value of the entries of the vector.
max_vector_size: An integer, representing the size of the vector to be generated.
recursive_step: An integer, representing the number of recursive calls. It is used as the stop criteria.
row_list: A list of integers, representing the generated vector.
Returns:
A list of integers, representing the vector with size max_vector_size and which entries are in increasing order.<|endoftext|> |
d35d008d5f8b766a2ef40edc3468de377bfeda425b8a1e4627bab348c9031b0e | def generate_symmetric_matrix(rows: List[List]) -> numpy.ndarray:
'\n Generates a symmmetric matrix from a upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A symmetric matrix, generated from the staggered rows.\n '
upper_triangular_matrix = generate_upper_triangular_matrix_from_rows(rows)
return ((upper_triangular_matrix + upper_triangular_matrix.T) - numpy.diag(numpy.diagonal(upper_triangular_matrix))) | Generates a symmmetric matrix from a upper triangular matrix.
Args:
rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,
the second list has k-1, and so on.
Returns:
A symmetric matrix, generated from the staggered rows. | discrete_fuzzy_operators/generators/tnorms/tnorms_iterative_generator_utils/tnorms_iterative_generator_utils.py | generate_symmetric_matrix | mmunar97/discrete-fuzzy-operators | 0 | python | def generate_symmetric_matrix(rows: List[List]) -> numpy.ndarray:
'\n Generates a symmmetric matrix from a upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A symmetric matrix, generated from the staggered rows.\n '
upper_triangular_matrix = generate_upper_triangular_matrix_from_rows(rows)
return ((upper_triangular_matrix + upper_triangular_matrix.T) - numpy.diag(numpy.diagonal(upper_triangular_matrix))) | def generate_symmetric_matrix(rows: List[List]) -> numpy.ndarray:
'\n Generates a symmmetric matrix from a upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A symmetric matrix, generated from the staggered rows.\n '
upper_triangular_matrix = generate_upper_triangular_matrix_from_rows(rows)
return ((upper_triangular_matrix + upper_triangular_matrix.T) - numpy.diag(numpy.diagonal(upper_triangular_matrix)))<|docstring|>Generates a symmmetric matrix from a upper triangular matrix.
Args:
rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,
the second list has k-1, and so on.
Returns:
A symmetric matrix, generated from the staggered rows.<|endoftext|> |
c9aa2601566df69c1c860df7a560c0cbca2daf213a59410d915b3c05547df980 | def generate_upper_triangular_matrix_from_rows(rows: List) -> numpy.ndarray:
'\n Write all rows in a matrix of zeros, aligned to the right, resulting in an upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A numpy array, representing the matrix which contains the lists of rows right-aligned, and filled with\n zeros in the remaining empty space..\n '
matrix = numpy.zeros((len(rows), len(rows[0])))
for i in range(0, len(rows)):
matrix[(i, i:len(rows[0]))] = rows[i]
return matrix | Write all rows in a matrix of zeros, aligned to the right, resulting in an upper triangular matrix.
Args:
rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,
the second list has k-1, and so on.
Returns:
A numpy array, representing the matrix which contains the lists of rows right-aligned, and filled with
zeros in the remaining empty space.. | discrete_fuzzy_operators/generators/tnorms/tnorms_iterative_generator_utils/tnorms_iterative_generator_utils.py | generate_upper_triangular_matrix_from_rows | mmunar97/discrete-fuzzy-operators | 0 | python | def generate_upper_triangular_matrix_from_rows(rows: List) -> numpy.ndarray:
'\n Write all rows in a matrix of zeros, aligned to the right, resulting in an upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A numpy array, representing the matrix which contains the lists of rows right-aligned, and filled with\n zeros in the remaining empty space..\n '
matrix = numpy.zeros((len(rows), len(rows[0])))
for i in range(0, len(rows)):
matrix[(i, i:len(rows[0]))] = rows[i]
return matrix | def generate_upper_triangular_matrix_from_rows(rows: List) -> numpy.ndarray:
'\n Write all rows in a matrix of zeros, aligned to the right, resulting in an upper triangular matrix.\n\n Args:\n rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,\n the second list has k-1, and so on.\n\n Returns:\n A numpy array, representing the matrix which contains the lists of rows right-aligned, and filled with\n zeros in the remaining empty space..\n '
matrix = numpy.zeros((len(rows), len(rows[0])))
for i in range(0, len(rows)):
matrix[(i, i:len(rows[0]))] = rows[i]
return matrix<|docstring|>Write all rows in a matrix of zeros, aligned to the right, resulting in an upper triangular matrix.
Args:
rows: A list of lists, containing the staggered rows of the matrix; that is, the first list has k elements,
the second list has k-1, and so on.
Returns:
A numpy array, representing the matrix which contains the lists of rows right-aligned, and filled with
zeros in the remaining empty space..<|endoftext|> |
1fa22ba91f73317d369414aabf0dfe4e0bac4940441c4b87f8f3c0aeeafc585a | def computeWidth(doc):
"\n Utility function for computing the 'actual' width of a text layout\n document, by taking the maximum line width.\n "
lines = []
for b in doc.blocks:
lines.extend(b.lines)
if (len(lines) == 0):
return 0
else:
return max([l.xMax for l in lines]) | Utility function for computing the 'actual' width of a text layout
document, by taking the maximum line width. | enso/messages/windows.py | computeWidth | blackdaemon/enso-launcher-continued | 7 | python | def computeWidth(doc):
"\n Utility function for computing the 'actual' width of a text layout\n document, by taking the maximum line width.\n "
lines = []
for b in doc.blocks:
lines.extend(b.lines)
if (len(lines) == 0):
return 0
else:
return max([l.xMax for l in lines]) | def computeWidth(doc):
"\n Utility function for computing the 'actual' width of a text layout\n document, by taking the maximum line width.\n "
lines = []
for b in doc.blocks:
lines.extend(b.lines)
if (len(lines) == 0):
return 0
else:
return max([l.xMax for l in lines])<|docstring|>Utility function for computing the 'actual' width of a text layout
document, by taking the maximum line width.<|endoftext|> |
78dc0826e1d61e591c4fa72106a01f2a449922a949993cf82b7acab0bee5b683 | def __init__(self, maxSize):
'\n Initialize the message window.\n '
self.__maxSize = maxSize
self.__currSize = (1, 1)
self.__currPos = (0, 0)
self._wind = None
self._context = None | Initialize the message window. | enso/messages/windows.py | __init__ | blackdaemon/enso-launcher-continued | 7 | python | def __init__(self, maxSize):
'\n \n '
self.__maxSize = maxSize
self.__currSize = (1, 1)
self.__currPos = (0, 0)
self._wind = None
self._context = None | def __init__(self, maxSize):
'\n \n '
self.__maxSize = maxSize
self.__currSize = (1, 1)
self.__currPos = (0, 0)
self._wind = None
self._context = None<|docstring|>Initialize the message window.<|endoftext|> |
9b2e9c62b9907edd17c751d6d681c8a80db69c35b869b029cd25821a22a6b9a8 | def __setupWindow(self):
"\n Creates the MessageWindow's underlying TransparentWindow and\n Cairo Context objects, once and for all.\n "
if (self._wind is None):
width = self.__maxSize[0]
height = self.__maxSize[1]
xPos = self.__currPos[0]
yPos = self.__currPos[1]
self._wind = TransparentWindow(xPos, yPos, width, height)
self._context = self._wind.makeCairoContext() | Creates the MessageWindow's underlying TransparentWindow and
Cairo Context objects, once and for all. | enso/messages/windows.py | __setupWindow | blackdaemon/enso-launcher-continued | 7 | python | def __setupWindow(self):
"\n Creates the MessageWindow's underlying TransparentWindow and\n Cairo Context objects, once and for all.\n "
if (self._wind is None):
width = self.__maxSize[0]
height = self.__maxSize[1]
xPos = self.__currPos[0]
yPos = self.__currPos[1]
self._wind = TransparentWindow(xPos, yPos, width, height)
self._context = self._wind.makeCairoContext() | def __setupWindow(self):
"\n Creates the MessageWindow's underlying TransparentWindow and\n Cairo Context objects, once and for all.\n "
if (self._wind is None):
width = self.__maxSize[0]
height = self.__maxSize[1]
xPos = self.__currPos[0]
yPos = self.__currPos[1]
self._wind = TransparentWindow(xPos, yPos, width, height)
self._context = self._wind.makeCairoContext()<|docstring|>Creates the MessageWindow's underlying TransparentWindow and
Cairo Context objects, once and for all.<|endoftext|> |
3b30385a6213b9e5c9494a75473d57c479f1ef15b26b37032795910f0417c582 | def setSize(self, width, height, refresh=True):
'\n Sets the current size of the message window the width, height.\n\n Using the function appropriately vastly improves performance,\n as it reduces the visible size of the window and the number of\n pixels that must be copied on window updates.\n '
assert (width <= self.getMaxSize()[0]), ('Window width (%d) is larger than maximum window width (%d)' % (width, self.getMaxSize()[0]))
assert (height <= self.getMaxSize()[1]), ('Window height (%d) is larger than maximum window height (%d)' % (height, self.getMaxSize()[1]))
self.__currSize = (width, height)
if ((self._wind is not None) and refresh):
self._wind.setSize(width, height) | Sets the current size of the message window the width, height.
Using the function appropriately vastly improves performance,
as it reduces the visible size of the window and the number of
pixels that must be copied on window updates. | enso/messages/windows.py | setSize | blackdaemon/enso-launcher-continued | 7 | python | def setSize(self, width, height, refresh=True):
'\n Sets the current size of the message window the width, height.\n\n Using the function appropriately vastly improves performance,\n as it reduces the visible size of the window and the number of\n pixels that must be copied on window updates.\n '
assert (width <= self.getMaxSize()[0]), ('Window width (%d) is larger than maximum window width (%d)' % (width, self.getMaxSize()[0]))
assert (height <= self.getMaxSize()[1]), ('Window height (%d) is larger than maximum window height (%d)' % (height, self.getMaxSize()[1]))
self.__currSize = (width, height)
if ((self._wind is not None) and refresh):
self._wind.setSize(width, height) | def setSize(self, width, height, refresh=True):
'\n Sets the current size of the message window the width, height.\n\n Using the function appropriately vastly improves performance,\n as it reduces the visible size of the window and the number of\n pixels that must be copied on window updates.\n '
assert (width <= self.getMaxSize()[0]), ('Window width (%d) is larger than maximum window width (%d)' % (width, self.getMaxSize()[0]))
assert (height <= self.getMaxSize()[1]), ('Window height (%d) is larger than maximum window height (%d)' % (height, self.getMaxSize()[1]))
self.__currSize = (width, height)
if ((self._wind is not None) and refresh):
self._wind.setSize(width, height)<|docstring|>Sets the current size of the message window the width, height.
Using the function appropriately vastly improves performance,
as it reduces the visible size of the window and the number of
pixels that must be copied on window updates.<|endoftext|> |
990ee474ab7b0f953155f04d6829a062160519b94d86b9396cf3cdcb18022b49 | def setPos(self, xPos, yPos):
'\n Sets the current position of the window to xPos, yPos, which\n should be in points.\n '
self.__currPos = (xPos, yPos)
if (self._wind is not None):
self._wind.setPosition(xPos, yPos) | Sets the current position of the window to xPos, yPos, which
should be in points. | enso/messages/windows.py | setPos | blackdaemon/enso-launcher-continued | 7 | python | def setPos(self, xPos, yPos):
'\n Sets the current position of the window to xPos, yPos, which\n should be in points.\n '
self.__currPos = (xPos, yPos)
if (self._wind is not None):
self._wind.setPosition(xPos, yPos) | def setPos(self, xPos, yPos):
'\n Sets the current position of the window to xPos, yPos, which\n should be in points.\n '
self.__currPos = (xPos, yPos)
if (self._wind is not None):
self._wind.setPosition(xPos, yPos)<|docstring|>Sets the current position of the window to xPos, yPos, which
should be in points.<|endoftext|> |
5a0b29b3a630aa778b692beade3c3e34d25e24d1b24fd1b05b049e9aba2e0733 | def hide(self):
'\n Sets the underlying TransparentWindow\'s size to (1,1) so that\n the window essentially vanishes. This effectively "hides" the\n window, causing it to cease interfering with performance of\n windows that are "underneath" the message window.\n '
self.__setupWindow()
self._wind.update() | Sets the underlying TransparentWindow's size to (1,1) so that
the window essentially vanishes. This effectively "hides" the
window, causing it to cease interfering with performance of
windows that are "underneath" the message window. | enso/messages/windows.py | hide | blackdaemon/enso-launcher-continued | 7 | python | def hide(self):
'\n Sets the underlying TransparentWindow\'s size to (1,1) so that\n the window essentially vanishes. This effectively "hides" the\n window, causing it to cease interfering with performance of\n windows that are "underneath" the message window.\n '
self.__setupWindow()
self._wind.update() | def hide(self):
'\n Sets the underlying TransparentWindow\'s size to (1,1) so that\n the window essentially vanishes. This effectively "hides" the\n window, causing it to cease interfering with performance of\n windows that are "underneath" the message window.\n '
self.__setupWindow()
self._wind.update()<|docstring|>Sets the underlying TransparentWindow's size to (1,1) so that
the window essentially vanishes. This effectively "hides" the
window, causing it to cease interfering with performance of
windows that are "underneath" the message window.<|endoftext|> |
ba6af483ab7d6a8063a79289f1c40d364cd8bd916ca24247565788d99c444f2a | def show(self):
'\n Sets the underlying TransparentWindow\'s size to the stored\n "current size" variable, essentially re-correlating the actual\n displayed rectangle on the screen to the size required by the\n MessageWindow\'s underlying content.\n '
self.__setupWindow()
(width, height) = self.getSize()
self.setSize(width, height, False)
self._wind.update() | Sets the underlying TransparentWindow's size to the stored
"current size" variable, essentially re-correlating the actual
displayed rectangle on the screen to the size required by the
MessageWindow's underlying content. | enso/messages/windows.py | show | blackdaemon/enso-launcher-continued | 7 | python | def show(self):
'\n Sets the underlying TransparentWindow\'s size to the stored\n "current size" variable, essentially re-correlating the actual\n displayed rectangle on the screen to the size required by the\n MessageWindow\'s underlying content.\n '
self.__setupWindow()
(width, height) = self.getSize()
self.setSize(width, height, False)
self._wind.update() | def show(self):
'\n Sets the underlying TransparentWindow\'s size to the stored\n "current size" variable, essentially re-correlating the actual\n displayed rectangle on the screen to the size required by the\n MessageWindow\'s underlying content.\n '
self.__setupWindow()
(width, height) = self.getSize()
self.setSize(width, height, False)
self._wind.update()<|docstring|>Sets the underlying TransparentWindow's size to the stored
"current size" variable, essentially re-correlating the actual
displayed rectangle on the screen to the size required by the
MessageWindow's underlying content.<|endoftext|> |
9ed67c8699c5657811f93561f6529c1dbb799c00a885faeb96b554a814c298e5 | def clearWindow(self):
'\n "Clears" the underlying cairo context.\n '
self.__setupWindow()
cr = self._context
cr.set_source_rgba(0, 0, 0, 0)
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.paint() | "Clears" the underlying cairo context. | enso/messages/windows.py | clearWindow | blackdaemon/enso-launcher-continued | 7 | python | def clearWindow(self):
'\n \n '
self.__setupWindow()
cr = self._context
cr.set_source_rgba(0, 0, 0, 0)
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.paint() | def clearWindow(self):
'\n \n '
self.__setupWindow()
cr = self._context
cr.set_source_rgba(0, 0, 0, 0)
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.paint()<|docstring|>"Clears" the underlying cairo context.<|endoftext|> |
a4c2deaec8754819258e53055c1d34f8c7efc5c4848bf77f164d30182d9501b9 | def get_choices(self):
'\n Returns the choices for the status card\n '
from seshdash.utils.model_tools import get_site_sensor_fields_choices
return get_site_sensor_fields_choices(self.sesh_site) | Returns the choices for the status card | seshdash/models.py | get_choices | GreatLakesEnergy/sesh-dash-beta | 11 | python | def get_choices(self):
'\n \n '
from seshdash.utils.model_tools import get_site_sensor_fields_choices
return get_site_sensor_fields_choices(self.sesh_site) | def get_choices(self):
'\n \n '
from seshdash.utils.model_tools import get_site_sensor_fields_choices
return get_site_sensor_fields_choices(self.sesh_site)<|docstring|>Returns the choices for the status card<|endoftext|> |
132aa3e48db64b6986af8ca3864104536ad7669847d0837fd97d8fc9b0d156e4 | def save(self, **kwargs):
'\n Generate numeric version of api key\n '
numeric_key = ''
for l in self.api_key:
numeric_key = (numeric_key + str(ord(l)))
self.api_key_numeric = numeric_key[:len(self.api_key)]
super(Sesh_RMC_Account, self).save(**kwargs) | Generate numeric version of api key | seshdash/models.py | save | GreatLakesEnergy/sesh-dash-beta | 11 | python | def save(self, **kwargs):
'\n \n '
numeric_key =
for l in self.api_key:
numeric_key = (numeric_key + str(ord(l)))
self.api_key_numeric = numeric_key[:len(self.api_key)]
super(Sesh_RMC_Account, self).save(**kwargs) | def save(self, **kwargs):
'\n \n '
numeric_key =
for l in self.api_key:
numeric_key = (numeric_key + str(ord(l)))
self.api_key_numeric = numeric_key[:len(self.api_key)]
super(Sesh_RMC_Account, self).save(**kwargs)<|docstring|>Generate numeric version of api key<|endoftext|> |
a4edb83f424d850ad467cfd00b48aa61195302470bd7001a25019b6464ed70eb | def get_fields(self):
'\n Returns the field of the sensor\n '
all_fields = [self.index1, self.index2, self.index3, self.index4, self.index5, self.index5, self.index6, self.index7, self.index8, self.index9, self.index10, self.index11, self.index12, self.index13, self.index14, self.index15, self.index16, self.index17, self.index18, self.index19, self.index20, self.index21, self.index22, self.index23, self.index24, self.index25, self.index26, self.index28, self.index29, self.index30, self.index31, self.index32, self.index33, self.index34, self.index35, self.index36, self.index37, self.index38, self.index39, self.index40, self.index41, self.index42]
fields = []
for field in all_fields:
if field:
fields.append(field)
return list(set(fields)) | Returns the field of the sensor | seshdash/models.py | get_fields | GreatLakesEnergy/sesh-dash-beta | 11 | python | def get_fields(self):
'\n \n '
all_fields = [self.index1, self.index2, self.index3, self.index4, self.index5, self.index5, self.index6, self.index7, self.index8, self.index9, self.index10, self.index11, self.index12, self.index13, self.index14, self.index15, self.index16, self.index17, self.index18, self.index19, self.index20, self.index21, self.index22, self.index23, self.index24, self.index25, self.index26, self.index28, self.index29, self.index30, self.index31, self.index32, self.index33, self.index34, self.index35, self.index36, self.index37, self.index38, self.index39, self.index40, self.index41, self.index42]
fields = []
for field in all_fields:
if field:
fields.append(field)
return list(set(fields)) | def get_fields(self):
'\n \n '
all_fields = [self.index1, self.index2, self.index3, self.index4, self.index5, self.index5, self.index6, self.index7, self.index8, self.index9, self.index10, self.index11, self.index12, self.index13, self.index14, self.index15, self.index16, self.index17, self.index18, self.index19, self.index20, self.index21, self.index22, self.index23, self.index24, self.index25, self.index26, self.index28, self.index29, self.index30, self.index31, self.index32, self.index33, self.index34, self.index35, self.index36, self.index37, self.index38, self.index39, self.index40, self.index41, self.index42]
fields = []
for field in all_fields:
if field:
fields.append(field)
return list(set(fields))<|docstring|>Returns the field of the sensor<|endoftext|> |
25c44471484b578b58977de9cd4a771384bda8e99e68a77705ac663049a61401 | def one_of_k_encoding_unk(self, x, allowable_set):
'Maps inputs not in the allowable set to the last element.'
if (x not in allowable_set):
x = allowable_set[(- 1)]
return list(map((lambda s: (x == s)), allowable_set)) | Maps inputs not in the allowable set to the last element. | model/framework/cardiotox/graph_model.py | one_of_k_encoding_unk | ersilia-os/eos2ta5 | 0 | python | def one_of_k_encoding_unk(self, x, allowable_set):
if (x not in allowable_set):
x = allowable_set[(- 1)]
return list(map((lambda s: (x == s)), allowable_set)) | def one_of_k_encoding_unk(self, x, allowable_set):
if (x not in allowable_set):
x = allowable_set[(- 1)]
return list(map((lambda s: (x == s)), allowable_set))<|docstring|>Maps inputs not in the allowable set to the last element.<|endoftext|> |
809bd7b95ef8880314d1add8831a1dea1b4d34b455f3942090e5b432d9cee29d | def ambil_teks_dalam_label(sup, ambil_italic=False):
'Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).\n\n :param sup: BeautifulSoup/Tag dari suatu label HTML\n :type sup: BeautifulSoup/Tag\n :returns: String semua teks dalam sup label HTML\n :rtype: str\n '
if ambil_italic:
italic = sup.find('i')
if italic:
sup = italic
return ''.join((i.strip() for i in sup.find_all(text=True, recursive=False))) | Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).
:param sup: BeautifulSoup/Tag dari suatu label HTML
:type sup: BeautifulSoup/Tag
:returns: String semua teks dalam sup label HTML
:rtype: str | kbbi/kbbi.py | ambil_teks_dalam_label | noaione/kbbi-python | 0 | python | def ambil_teks_dalam_label(sup, ambil_italic=False):
'Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).\n\n :param sup: BeautifulSoup/Tag dari suatu label HTML\n :type sup: BeautifulSoup/Tag\n :returns: String semua teks dalam sup label HTML\n :rtype: str\n '
if ambil_italic:
italic = sup.find('i')
if italic:
sup = italic
return .join((i.strip() for i in sup.find_all(text=True, recursive=False))) | def ambil_teks_dalam_label(sup, ambil_italic=False):
'Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).\n\n :param sup: BeautifulSoup/Tag dari suatu label HTML\n :type sup: BeautifulSoup/Tag\n :returns: String semua teks dalam sup label HTML\n :rtype: str\n '
if ambil_italic:
italic = sup.find('i')
if italic:
sup = italic
return .join((i.strip() for i in sup.find_all(text=True, recursive=False)))<|docstring|>Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya).
:param sup: BeautifulSoup/Tag dari suatu label HTML
:type sup: BeautifulSoup/Tag
:returns: String semua teks dalam sup label HTML
:rtype: str<|endoftext|> |
d90b8a58bbab4b7587b6b19d9a717f954eb3c8ea897f51a9920c4acf9f11373e | def main(argv=None):
'Program utama dengan CLI.'
if (argv is None):
argv = sys.argv[1:]
args = _parse_args(argv)
try:
laman = KBBI(args.laman)
except (TidakDitemukan, TerjadiKesalahan, BatasSehari) as e:
print(e)
else:
print(_keluaran(laman, args)) | Program utama dengan CLI. | kbbi/kbbi.py | main | noaione/kbbi-python | 0 | python | def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
args = _parse_args(argv)
try:
laman = KBBI(args.laman)
except (TidakDitemukan, TerjadiKesalahan, BatasSehari) as e:
print(e)
else:
print(_keluaran(laman, args)) | def main(argv=None):
if (argv is None):
argv = sys.argv[1:]
args = _parse_args(argv)
try:
laman = KBBI(args.laman)
except (TidakDitemukan, TerjadiKesalahan, BatasSehari) as e:
print(e)
else:
print(_keluaran(laman, args))<|docstring|>Program utama dengan CLI.<|endoftext|> |
9769a4fa6b5b14fb78ff4e205542117c980b7dd856eb18082930d31692c9538d | def __init__(self, kueri):
'Membuat objek KBBI baru berdasarkan kueri yang diberikan.\n\n :param kueri: Kata kunci pencarian\n :type kueri: str\n '
self.nama = kueri
self._init_pranala()
laman = requests.get(self.pranala)
self._cek_galat(laman)
self._init_entri(laman) | Membuat objek KBBI baru berdasarkan kueri yang diberikan.
:param kueri: Kata kunci pencarian
:type kueri: str | kbbi/kbbi.py | __init__ | noaione/kbbi-python | 0 | python | def __init__(self, kueri):
'Membuat objek KBBI baru berdasarkan kueri yang diberikan.\n\n :param kueri: Kata kunci pencarian\n :type kueri: str\n '
self.nama = kueri
self._init_pranala()
laman = requests.get(self.pranala)
self._cek_galat(laman)
self._init_entri(laman) | def __init__(self, kueri):
'Membuat objek KBBI baru berdasarkan kueri yang diberikan.\n\n :param kueri: Kata kunci pencarian\n :type kueri: str\n '
self.nama = kueri
self._init_pranala()
laman = requests.get(self.pranala)
self._cek_galat(laman)
self._init_entri(laman)<|docstring|>Membuat objek KBBI baru berdasarkan kueri yang diberikan.
:param kueri: Kata kunci pencarian
:type kueri: str<|endoftext|> |
8576c5da1df0efa940cb08cdc0ad25683a1e9fb2850c610b86fb172fb9e8c73b | def serialisasi(self):
'Mengembalikan hasil serialisasi objek KBBI ini.\n\n :returns: Dictionary hasil serialisasi\n :rtype: dict\n '
return {'pranala': self.pranala, 'entri': [entri.serialisasi() for entri in self.entri]} | Mengembalikan hasil serialisasi objek KBBI ini.
:returns: Dictionary hasil serialisasi
:rtype: dict | kbbi/kbbi.py | serialisasi | noaione/kbbi-python | 0 | python | def serialisasi(self):
'Mengembalikan hasil serialisasi objek KBBI ini.\n\n :returns: Dictionary hasil serialisasi\n :rtype: dict\n '
return {'pranala': self.pranala, 'entri': [entri.serialisasi() for entri in self.entri]} | def serialisasi(self):
'Mengembalikan hasil serialisasi objek KBBI ini.\n\n :returns: Dictionary hasil serialisasi\n :rtype: dict\n '
return {'pranala': self.pranala, 'entri': [entri.serialisasi() for entri in self.entri]}<|docstring|>Mengembalikan hasil serialisasi objek KBBI ini.
:returns: Dictionary hasil serialisasi
:rtype: dict<|endoftext|> |
cac0b66de0664e21745f406c365f5c093502a417e8c91c745d01570d4757589e | def add_module_template(self, module_name, create_options={}, is_debug=False):
'Add a module template to the deployment manifest'
new_module = {'version': '1.0', 'type': 'docker', 'status': 'running', 'restartPolicy': 'always', 'settings': {'image': DeploymentManifest.get_image_placeholder(module_name, is_debug), 'createOptions': create_options}}
try:
self.utility.nested_set(self._get_module_content(), ['$edgeAgent', 'properties.desired', 'modules', module_name], new_module)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))
self.add_default_route(module_name) | Add a module template to the deployment manifest | iotedgedev/deploymentmanifest.py | add_module_template | jporcenaluk/iotedgedev | 0 | python | def add_module_template(self, module_name, create_options={}, is_debug=False):
new_module = {'version': '1.0', 'type': 'docker', 'status': 'running', 'restartPolicy': 'always', 'settings': {'image': DeploymentManifest.get_image_placeholder(module_name, is_debug), 'createOptions': create_options}}
try:
self.utility.nested_set(self._get_module_content(), ['$edgeAgent', 'properties.desired', 'modules', module_name], new_module)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))
self.add_default_route(module_name) | def add_module_template(self, module_name, create_options={}, is_debug=False):
new_module = {'version': '1.0', 'type': 'docker', 'status': 'running', 'restartPolicy': 'always', 'settings': {'image': DeploymentManifest.get_image_placeholder(module_name, is_debug), 'createOptions': create_options}}
try:
self.utility.nested_set(self._get_module_content(), ['$edgeAgent', 'properties.desired', 'modules', module_name], new_module)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))
self.add_default_route(module_name)<|docstring|>Add a module template to the deployment manifest<|endoftext|> |
16f39ec4aecb3126e4360dd8687d022fbfbb34cfa9b7a97ecb3ae1dcd54f382a | def add_default_route(self, module_name):
'Add a default route to send messages to IoT Hub'
new_route_name = '{0}ToIoTHub'.format(module_name)
new_route = 'FROM /messages/modules/{0}/outputs/* INTO $upstream'.format(module_name)
try:
self.utility.nested_set(self._get_module_content(), ['$edgeHub', 'properties.desired', 'routes', new_route_name], new_route)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | Add a default route to send messages to IoT Hub | iotedgedev/deploymentmanifest.py | add_default_route | jporcenaluk/iotedgedev | 0 | python | def add_default_route(self, module_name):
new_route_name = '{0}ToIoTHub'.format(module_name)
new_route = 'FROM /messages/modules/{0}/outputs/* INTO $upstream'.format(module_name)
try:
self.utility.nested_set(self._get_module_content(), ['$edgeHub', 'properties.desired', 'routes', new_route_name], new_route)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | def add_default_route(self, module_name):
new_route_name = '{0}ToIoTHub'.format(module_name)
new_route = 'FROM /messages/modules/{0}/outputs/* INTO $upstream'.format(module_name)
try:
self.utility.nested_set(self._get_module_content(), ['$edgeHub', 'properties.desired', 'routes', new_route_name], new_route)
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))<|docstring|>Add a default route to send messages to IoT Hub<|endoftext|> |
71caa82bdebf7d1d84acb4c2c41b1fa84d16c95c92b9e5933687ce827534fc8f | def get_user_modules(self):
'Get user modules from deployment manifest'
try:
return self.get_desired_property('$edgeAgent', 'modules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | Get user modules from deployment manifest | iotedgedev/deploymentmanifest.py | get_user_modules | jporcenaluk/iotedgedev | 0 | python | def get_user_modules(self):
try:
return self.get_desired_property('$edgeAgent', 'modules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | def get_user_modules(self):
try:
return self.get_desired_property('$edgeAgent', 'modules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))<|docstring|>Get user modules from deployment manifest<|endoftext|> |
9e535381cf44b5dc949adb80dd9d368dcbfca3491755a6271c400ac882775835 | def get_system_modules(self):
'Get system modules from deployment manifest'
try:
return self.get_desired_property('$edgeAgent', 'systemModules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | Get system modules from deployment manifest | iotedgedev/deploymentmanifest.py | get_system_modules | jporcenaluk/iotedgedev | 0 | python | def get_system_modules(self):
try:
return self.get_desired_property('$edgeAgent', 'systemModules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path)) | def get_system_modules(self):
try:
return self.get_desired_property('$edgeAgent', 'systemModules')
except KeyError as err:
raise KeyError('Missing key {0} in file {1}'.format(err, self.path))<|docstring|>Get system modules from deployment manifest<|endoftext|> |
dec7a8c1739aef5fc8a9c28a4c08b1186250b1602781b52d3a30d72cbcdb958b | def dump(self, path=None):
'Dump the JSON to the disk'
if (path is None):
path = self.path
with open(path, 'w') as deployment_manifest:
json.dump(self.json, deployment_manifest, indent=2) | Dump the JSON to the disk | iotedgedev/deploymentmanifest.py | dump | jporcenaluk/iotedgedev | 0 | python | def dump(self, path=None):
if (path is None):
path = self.path
with open(path, 'w') as deployment_manifest:
json.dump(self.json, deployment_manifest, indent=2) | def dump(self, path=None):
if (path is None):
path = self.path
with open(path, 'w') as deployment_manifest:
json.dump(self.json, deployment_manifest, indent=2)<|docstring|>Dump the JSON to the disk<|endoftext|> |
100c45908aa9bfe47957d950bec6d367c4a95e3e478e0b2c228e74c081388a44 | def instrument_view(scipp_obj=None, positions='position', pixel_size=None, components=None, **kwargs):
'\n :param scipp_obj: scipp object holding geometries\n :param positions: Key for coord/attr holding positions to use for pixels\n :param pixel_size: Custom pixel size to use for detector pixels\n :param components: Dictionary containing display names and corresponding\n settings (also a Dictionary) for additional components to display\n items with known positions to be shown\n :param kwargs: Additional keyword arguments to pass to scipp.plotting.plot\n :return: The 3D plot object\n\n Plot a 3D view of the instrument, using the `position` coordinate as the\n detector vector positions.\n Use the `positions` argument to change the vectors used as pixel positions.\n Sliders are added to navigate extra dimensions.\n Spatial slicing and pixel opacity control is available using the controls\n below the scene.\n Use the `pixel_size` argument to specify the size of the detectors.\n If no `pixel_size` is given, a guess is performed based on the distance\n between the positions of the first two pixel positions.\n The aspect ratio of the positions is preserved by default, but this can\n be changed to automatic scaling using `aspect="equal"`.\n\n `components` dictionary uses the key as the name to display the component.\n This can be any desired name, it does not have to relate to the input\n `scipp_obj` naming.\n The value for each entry is itself a dictionary that provides the display\n settings and requires:\n\n * `center` - scipp scalar vector describing position to place item at.\n * `size` - scipp scalar vector describing the bounding box to use in the\n same length units as positions\n * `type` - known shape type to use.\n Valid types are: \'box\', \'cylinder\' or \'disk\'.\n\n Optional arguments are:\n\n * `color` - a hexadecimal color code such as #F00000 to use as fill or\n line color\n * `wireframe` - wireframe is a bool that defaults to False. If set to True,\n the returned geometrical shape is a wireframe instead of a shape with\n opaque faces\n '
if (not p3):
raise _pythreejs_import_error
from scipp.plotting import plot
from scipp.plotting.objects import PlotDict
positions_var = scipp_obj.meta[positions]
if (pixel_size is None):
pos_array = positions_var.values
if (len(pos_array) > 1):
pixel_size = np.linalg.norm((pos_array[1] - pos_array[0]))
plt = plot(scipp_obj, projection='3d', positions=positions, pixel_size=pixel_size, **kwargs)
if (components and (not isinstance(plt, PlotDict))):
scene = plt.view.figure.scene
_plot_components(scipp_obj, components, positions_var, scene)
return plt | :param scipp_obj: scipp object holding geometries
:param positions: Key for coord/attr holding positions to use for pixels
:param pixel_size: Custom pixel size to use for detector pixels
:param components: Dictionary containing display names and corresponding
settings (also a Dictionary) for additional components to display
items with known positions to be shown
:param kwargs: Additional keyword arguments to pass to scipp.plotting.plot
:return: The 3D plot object
Plot a 3D view of the instrument, using the `position` coordinate as the
detector vector positions.
Use the `positions` argument to change the vectors used as pixel positions.
Sliders are added to navigate extra dimensions.
Spatial slicing and pixel opacity control is available using the controls
below the scene.
Use the `pixel_size` argument to specify the size of the detectors.
If no `pixel_size` is given, a guess is performed based on the distance
between the positions of the first two pixel positions.
The aspect ratio of the positions is preserved by default, but this can
be changed to automatic scaling using `aspect="equal"`.
`components` dictionary uses the key as the name to display the component.
This can be any desired name, it does not have to relate to the input
`scipp_obj` naming.
The value for each entry is itself a dictionary that provides the display
settings and requires:
* `center` - scipp scalar vector describing position to place item at.
* `size` - scipp scalar vector describing the bounding box to use in the
same length units as positions
* `type` - known shape type to use.
Valid types are: 'box', 'cylinder' or 'disk'.
Optional arguments are:
* `color` - a hexadecimal color code such as #F00000 to use as fill or
line color
* `wireframe` - wireframe is a bool that defaults to False. If set to True,
the returned geometrical shape is a wireframe instead of a shape with
opaque faces | python/src/scippneutron/instrument_view.py | instrument_view | arm61/scippneutron | 2 | python | def instrument_view(scipp_obj=None, positions='position', pixel_size=None, components=None, **kwargs):
'\n :param scipp_obj: scipp object holding geometries\n :param positions: Key for coord/attr holding positions to use for pixels\n :param pixel_size: Custom pixel size to use for detector pixels\n :param components: Dictionary containing display names and corresponding\n settings (also a Dictionary) for additional components to display\n items with known positions to be shown\n :param kwargs: Additional keyword arguments to pass to scipp.plotting.plot\n :return: The 3D plot object\n\n Plot a 3D view of the instrument, using the `position` coordinate as the\n detector vector positions.\n Use the `positions` argument to change the vectors used as pixel positions.\n Sliders are added to navigate extra dimensions.\n Spatial slicing and pixel opacity control is available using the controls\n below the scene.\n Use the `pixel_size` argument to specify the size of the detectors.\n If no `pixel_size` is given, a guess is performed based on the distance\n between the positions of the first two pixel positions.\n The aspect ratio of the positions is preserved by default, but this can\n be changed to automatic scaling using `aspect="equal"`.\n\n `components` dictionary uses the key as the name to display the component.\n This can be any desired name, it does not have to relate to the input\n `scipp_obj` naming.\n The value for each entry is itself a dictionary that provides the display\n settings and requires:\n\n * `center` - scipp scalar vector describing position to place item at.\n * `size` - scipp scalar vector describing the bounding box to use in the\n same length units as positions\n * `type` - known shape type to use.\n Valid types are: \'box\', \'cylinder\' or \'disk\'.\n\n Optional arguments are:\n\n * `color` - a hexadecimal color code such as #F00000 to use as fill or\n line color\n * `wireframe` - wireframe is a bool that defaults to False. If set to True,\n the returned geometrical shape is a wireframe instead of a shape with\n opaque faces\n '
if (not p3):
raise _pythreejs_import_error
from scipp.plotting import plot
from scipp.plotting.objects import PlotDict
positions_var = scipp_obj.meta[positions]
if (pixel_size is None):
pos_array = positions_var.values
if (len(pos_array) > 1):
pixel_size = np.linalg.norm((pos_array[1] - pos_array[0]))
plt = plot(scipp_obj, projection='3d', positions=positions, pixel_size=pixel_size, **kwargs)
if (components and (not isinstance(plt, PlotDict))):
scene = plt.view.figure.scene
_plot_components(scipp_obj, components, positions_var, scene)
return plt | def instrument_view(scipp_obj=None, positions='position', pixel_size=None, components=None, **kwargs):
'\n :param scipp_obj: scipp object holding geometries\n :param positions: Key for coord/attr holding positions to use for pixels\n :param pixel_size: Custom pixel size to use for detector pixels\n :param components: Dictionary containing display names and corresponding\n settings (also a Dictionary) for additional components to display\n items with known positions to be shown\n :param kwargs: Additional keyword arguments to pass to scipp.plotting.plot\n :return: The 3D plot object\n\n Plot a 3D view of the instrument, using the `position` coordinate as the\n detector vector positions.\n Use the `positions` argument to change the vectors used as pixel positions.\n Sliders are added to navigate extra dimensions.\n Spatial slicing and pixel opacity control is available using the controls\n below the scene.\n Use the `pixel_size` argument to specify the size of the detectors.\n If no `pixel_size` is given, a guess is performed based on the distance\n between the positions of the first two pixel positions.\n The aspect ratio of the positions is preserved by default, but this can\n be changed to automatic scaling using `aspect="equal"`.\n\n `components` dictionary uses the key as the name to display the component.\n This can be any desired name, it does not have to relate to the input\n `scipp_obj` naming.\n The value for each entry is itself a dictionary that provides the display\n settings and requires:\n\n * `center` - scipp scalar vector describing position to place item at.\n * `size` - scipp scalar vector describing the bounding box to use in the\n same length units as positions\n * `type` - known shape type to use.\n Valid types are: \'box\', \'cylinder\' or \'disk\'.\n\n Optional arguments are:\n\n * `color` - a hexadecimal color code such as #F00000 to use as fill or\n line color\n * `wireframe` - wireframe is a bool that defaults to False. If set to True,\n the returned geometrical shape is a wireframe instead of a shape with\n opaque faces\n '
if (not p3):
raise _pythreejs_import_error
from scipp.plotting import plot
from scipp.plotting.objects import PlotDict
positions_var = scipp_obj.meta[positions]
if (pixel_size is None):
pos_array = positions_var.values
if (len(pos_array) > 1):
pixel_size = np.linalg.norm((pos_array[1] - pos_array[0]))
plt = plot(scipp_obj, projection='3d', positions=positions, pixel_size=pixel_size, **kwargs)
if (components and (not isinstance(plt, PlotDict))):
scene = plt.view.figure.scene
_plot_components(scipp_obj, components, positions_var, scene)
return plt<|docstring|>:param scipp_obj: scipp object holding geometries
:param positions: Key for coord/attr holding positions to use for pixels
:param pixel_size: Custom pixel size to use for detector pixels
:param components: Dictionary containing display names and corresponding
settings (also a Dictionary) for additional components to display
items with known positions to be shown
:param kwargs: Additional keyword arguments to pass to scipp.plotting.plot
:return: The 3D plot object
Plot a 3D view of the instrument, using the `position` coordinate as the
detector vector positions.
Use the `positions` argument to change the vectors used as pixel positions.
Sliders are added to navigate extra dimensions.
Spatial slicing and pixel opacity control is available using the controls
below the scene.
Use the `pixel_size` argument to specify the size of the detectors.
If no `pixel_size` is given, a guess is performed based on the distance
between the positions of the first two pixel positions.
The aspect ratio of the positions is preserved by default, but this can
be changed to automatic scaling using `aspect="equal"`.
`components` dictionary uses the key as the name to display the component.
This can be any desired name, it does not have to relate to the input
`scipp_obj` naming.
The value for each entry is itself a dictionary that provides the display
settings and requires:
* `center` - scipp scalar vector describing position to place item at.
* `size` - scipp scalar vector describing the bounding box to use in the
same length units as positions
* `type` - known shape type to use.
Valid types are: 'box', 'cylinder' or 'disk'.
Optional arguments are:
* `color` - a hexadecimal color code such as #F00000 to use as fill or
line color
* `wireframe` - wireframe is a bool that defaults to False. If set to True,
the returned geometrical shape is a wireframe instead of a shape with
opaque faces<|endoftext|> |
fdbab3efb2006e6e978c1ab4cd0e98a63b49bd7ab670a7d06c5b794c02a48926 | def update_alarm(self, alarm):
'Update alarm.'
data = alarm.as_dict()
self.db.alarm.update({'alarm_id': alarm.alarm_id}, {'$set': data}, upsert=True)
stored_alarm = self.db.alarm.find({'alarm_id': alarm.alarm_id})[0]
del stored_alarm['_id']
self._ensure_encapsulated_rule_format(stored_alarm)
self._ensure_time_constraints(stored_alarm)
return models.Alarm(**stored_alarm) | Update alarm. | ceilometer/alarm/storage/pymongo_base.py | update_alarm | glove747/liberty-ceilometer | 1 | python | def update_alarm(self, alarm):
data = alarm.as_dict()
self.db.alarm.update({'alarm_id': alarm.alarm_id}, {'$set': data}, upsert=True)
stored_alarm = self.db.alarm.find({'alarm_id': alarm.alarm_id})[0]
del stored_alarm['_id']
self._ensure_encapsulated_rule_format(stored_alarm)
self._ensure_time_constraints(stored_alarm)
return models.Alarm(**stored_alarm) | def update_alarm(self, alarm):
data = alarm.as_dict()
self.db.alarm.update({'alarm_id': alarm.alarm_id}, {'$set': data}, upsert=True)
stored_alarm = self.db.alarm.find({'alarm_id': alarm.alarm_id})[0]
del stored_alarm['_id']
self._ensure_encapsulated_rule_format(stored_alarm)
self._ensure_time_constraints(stored_alarm)
return models.Alarm(**stored_alarm)<|docstring|>Update alarm.<|endoftext|> |
ccd5fb3d7b2aea705a1e5196ec58127093af2dfdfafefbbe83fd211546371216 | def delete_alarm(self, alarm_id):
'Delete an alarm and its history data.'
self.db.alarm.remove({'alarm_id': alarm_id})
self.db.alarm_history.remove({'alarm_id': alarm_id}) | Delete an alarm and its history data. | ceilometer/alarm/storage/pymongo_base.py | delete_alarm | glove747/liberty-ceilometer | 1 | python | def delete_alarm(self, alarm_id):
self.db.alarm.remove({'alarm_id': alarm_id})
self.db.alarm_history.remove({'alarm_id': alarm_id}) | def delete_alarm(self, alarm_id):
self.db.alarm.remove({'alarm_id': alarm_id})
self.db.alarm_history.remove({'alarm_id': alarm_id})<|docstring|>Delete an alarm and its history data.<|endoftext|> |
8a2470b5c17dab2d29fc7ade01de1ebf20d91d41125522ac855bb8217a3519f4 | def record_alarm_change(self, alarm_change):
'Record alarm change event.'
self.db.alarm_history.insert(alarm_change.copy()) | Record alarm change event. | ceilometer/alarm/storage/pymongo_base.py | record_alarm_change | glove747/liberty-ceilometer | 1 | python | def record_alarm_change(self, alarm_change):
self.db.alarm_history.insert(alarm_change.copy()) | def record_alarm_change(self, alarm_change):
self.db.alarm_history.insert(alarm_change.copy())<|docstring|>Record alarm change event.<|endoftext|> |
448a69f9ad1bc1c949f6bc68ff2dd4e53bc4c7eccced692c1fc93800ce186ded | def get_alarms(self, name=None, user=None, state=None, meter=None, project=None, enabled=None, alarm_id=None, alarm_type=None, severity=None):
'Yields a lists of alarms that match filters.\n\n :param name: Optional name for alarm.\n :param user: Optional ID for user that owns the resource.\n :param state: Optional string for alarm state.\n :param meter: Optional string for alarms associated with meter.\n :param project: Optional ID for project that owns the resource.\n :param enabled: Optional boolean to list disable alarm.\n :param alarm_id: Optional alarm_id to return one alarm.\n :param alarm_type: Optional alarm type.\n :param severity: Optional alarm severity.\n '
q = {}
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (name is not None):
q['name'] = name
if (enabled is not None):
q['enabled'] = enabled
if (alarm_id is not None):
q['alarm_id'] = alarm_id
if (state is not None):
q['state'] = state
if (meter is not None):
q['rule.meter_name'] = meter
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
return self._retrieve_alarms(q, [('timestamp', pymongo.DESCENDING)], None) | Yields a lists of alarms that match filters.
:param name: Optional name for alarm.
:param user: Optional ID for user that owns the resource.
:param state: Optional string for alarm state.
:param meter: Optional string for alarms associated with meter.
:param project: Optional ID for project that owns the resource.
:param enabled: Optional boolean to list disable alarm.
:param alarm_id: Optional alarm_id to return one alarm.
:param alarm_type: Optional alarm type.
:param severity: Optional alarm severity. | ceilometer/alarm/storage/pymongo_base.py | get_alarms | glove747/liberty-ceilometer | 1 | python | def get_alarms(self, name=None, user=None, state=None, meter=None, project=None, enabled=None, alarm_id=None, alarm_type=None, severity=None):
'Yields a lists of alarms that match filters.\n\n :param name: Optional name for alarm.\n :param user: Optional ID for user that owns the resource.\n :param state: Optional string for alarm state.\n :param meter: Optional string for alarms associated with meter.\n :param project: Optional ID for project that owns the resource.\n :param enabled: Optional boolean to list disable alarm.\n :param alarm_id: Optional alarm_id to return one alarm.\n :param alarm_type: Optional alarm type.\n :param severity: Optional alarm severity.\n '
q = {}
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (name is not None):
q['name'] = name
if (enabled is not None):
q['enabled'] = enabled
if (alarm_id is not None):
q['alarm_id'] = alarm_id
if (state is not None):
q['state'] = state
if (meter is not None):
q['rule.meter_name'] = meter
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
return self._retrieve_alarms(q, [('timestamp', pymongo.DESCENDING)], None) | def get_alarms(self, name=None, user=None, state=None, meter=None, project=None, enabled=None, alarm_id=None, alarm_type=None, severity=None):
'Yields a lists of alarms that match filters.\n\n :param name: Optional name for alarm.\n :param user: Optional ID for user that owns the resource.\n :param state: Optional string for alarm state.\n :param meter: Optional string for alarms associated with meter.\n :param project: Optional ID for project that owns the resource.\n :param enabled: Optional boolean to list disable alarm.\n :param alarm_id: Optional alarm_id to return one alarm.\n :param alarm_type: Optional alarm type.\n :param severity: Optional alarm severity.\n '
q = {}
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (name is not None):
q['name'] = name
if (enabled is not None):
q['enabled'] = enabled
if (alarm_id is not None):
q['alarm_id'] = alarm_id
if (state is not None):
q['state'] = state
if (meter is not None):
q['rule.meter_name'] = meter
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
return self._retrieve_alarms(q, [('timestamp', pymongo.DESCENDING)], None)<|docstring|>Yields a lists of alarms that match filters.
:param name: Optional name for alarm.
:param user: Optional ID for user that owns the resource.
:param state: Optional string for alarm state.
:param meter: Optional string for alarms associated with meter.
:param project: Optional ID for project that owns the resource.
:param enabled: Optional boolean to list disable alarm.
:param alarm_id: Optional alarm_id to return one alarm.
:param alarm_type: Optional alarm type.
:param severity: Optional alarm severity.<|endoftext|> |
30e3cbd0f171f81c6fdda6c4b52cb1ab5bc68dd93413a8b84d3fbefc6b60ec17 | def get_alarm_changes(self, alarm_id, on_behalf_of, user=None, project=None, alarm_type=None, severity=None, start_timestamp=None, start_timestamp_op=None, end_timestamp=None, end_timestamp_op=None):
'Yields list of AlarmChanges describing alarm history\n\n Changes are always sorted in reverse order of occurrence, given\n the importance of currency.\n\n Segregation for non-administrative users is done on the basis\n of the on_behalf_of parameter. This allows such users to have\n visibility on both the changes initiated by themselves directly\n (generally creation, rule changes, or deletion) and also on those\n changes initiated on their behalf by the alarming service (state\n transitions after alarm thresholds are crossed).\n\n :param alarm_id: ID of alarm to return changes for\n :param on_behalf_of: ID of tenant to scope changes query (None for\n administrative user, indicating all projects)\n :param user: Optional ID of user to return changes for\n :param project: Optional ID of project to return changes for\n :param alarm_type: Optional change type\n :param severity: Optional change severity\n :param start_timestamp: Optional modified timestamp start range\n :param start_timestamp_op: Optional timestamp start range operation\n :param end_timestamp: Optional modified timestamp end range\n :param end_timestamp_op: Optional timestamp end range operation\n '
q = dict(alarm_id=alarm_id)
if (on_behalf_of is not None):
q['on_behalf_of'] = on_behalf_of
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
if (start_timestamp or end_timestamp):
ts_range = pymongo_utils.make_timestamp_range(start_timestamp, end_timestamp, start_timestamp_op, end_timestamp_op)
if ts_range:
q['timestamp'] = ts_range
return self._retrieve_alarm_changes(q, [('timestamp', pymongo.DESCENDING)], None) | Yields list of AlarmChanges describing alarm history
Changes are always sorted in reverse order of occurrence, given
the importance of currency.
Segregation for non-administrative users is done on the basis
of the on_behalf_of parameter. This allows such users to have
visibility on both the changes initiated by themselves directly
(generally creation, rule changes, or deletion) and also on those
changes initiated on their behalf by the alarming service (state
transitions after alarm thresholds are crossed).
:param alarm_id: ID of alarm to return changes for
:param on_behalf_of: ID of tenant to scope changes query (None for
administrative user, indicating all projects)
:param user: Optional ID of user to return changes for
:param project: Optional ID of project to return changes for
:param alarm_type: Optional change type
:param severity: Optional change severity
:param start_timestamp: Optional modified timestamp start range
:param start_timestamp_op: Optional timestamp start range operation
:param end_timestamp: Optional modified timestamp end range
:param end_timestamp_op: Optional timestamp end range operation | ceilometer/alarm/storage/pymongo_base.py | get_alarm_changes | glove747/liberty-ceilometer | 1 | python | def get_alarm_changes(self, alarm_id, on_behalf_of, user=None, project=None, alarm_type=None, severity=None, start_timestamp=None, start_timestamp_op=None, end_timestamp=None, end_timestamp_op=None):
'Yields list of AlarmChanges describing alarm history\n\n Changes are always sorted in reverse order of occurrence, given\n the importance of currency.\n\n Segregation for non-administrative users is done on the basis\n of the on_behalf_of parameter. This allows such users to have\n visibility on both the changes initiated by themselves directly\n (generally creation, rule changes, or deletion) and also on those\n changes initiated on their behalf by the alarming service (state\n transitions after alarm thresholds are crossed).\n\n :param alarm_id: ID of alarm to return changes for\n :param on_behalf_of: ID of tenant to scope changes query (None for\n administrative user, indicating all projects)\n :param user: Optional ID of user to return changes for\n :param project: Optional ID of project to return changes for\n :param alarm_type: Optional change type\n :param severity: Optional change severity\n :param start_timestamp: Optional modified timestamp start range\n :param start_timestamp_op: Optional timestamp start range operation\n :param end_timestamp: Optional modified timestamp end range\n :param end_timestamp_op: Optional timestamp end range operation\n '
q = dict(alarm_id=alarm_id)
if (on_behalf_of is not None):
q['on_behalf_of'] = on_behalf_of
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
if (start_timestamp or end_timestamp):
ts_range = pymongo_utils.make_timestamp_range(start_timestamp, end_timestamp, start_timestamp_op, end_timestamp_op)
if ts_range:
q['timestamp'] = ts_range
return self._retrieve_alarm_changes(q, [('timestamp', pymongo.DESCENDING)], None) | def get_alarm_changes(self, alarm_id, on_behalf_of, user=None, project=None, alarm_type=None, severity=None, start_timestamp=None, start_timestamp_op=None, end_timestamp=None, end_timestamp_op=None):
'Yields list of AlarmChanges describing alarm history\n\n Changes are always sorted in reverse order of occurrence, given\n the importance of currency.\n\n Segregation for non-administrative users is done on the basis\n of the on_behalf_of parameter. This allows such users to have\n visibility on both the changes initiated by themselves directly\n (generally creation, rule changes, or deletion) and also on those\n changes initiated on their behalf by the alarming service (state\n transitions after alarm thresholds are crossed).\n\n :param alarm_id: ID of alarm to return changes for\n :param on_behalf_of: ID of tenant to scope changes query (None for\n administrative user, indicating all projects)\n :param user: Optional ID of user to return changes for\n :param project: Optional ID of project to return changes for\n :param alarm_type: Optional change type\n :param severity: Optional change severity\n :param start_timestamp: Optional modified timestamp start range\n :param start_timestamp_op: Optional timestamp start range operation\n :param end_timestamp: Optional modified timestamp end range\n :param end_timestamp_op: Optional timestamp end range operation\n '
q = dict(alarm_id=alarm_id)
if (on_behalf_of is not None):
q['on_behalf_of'] = on_behalf_of
if (user is not None):
q['user_id'] = user
if (project is not None):
q['project_id'] = project
if (alarm_type is not None):
q['type'] = alarm_type
if (severity is not None):
q['severity'] = severity
if (start_timestamp or end_timestamp):
ts_range = pymongo_utils.make_timestamp_range(start_timestamp, end_timestamp, start_timestamp_op, end_timestamp_op)
if ts_range:
q['timestamp'] = ts_range
return self._retrieve_alarm_changes(q, [('timestamp', pymongo.DESCENDING)], None)<|docstring|>Yields list of AlarmChanges describing alarm history
Changes are always sorted in reverse order of occurrence, given
the importance of currency.
Segregation for non-administrative users is done on the basis
of the on_behalf_of parameter. This allows such users to have
visibility on both the changes initiated by themselves directly
(generally creation, rule changes, or deletion) and also on those
changes initiated on their behalf by the alarming service (state
transitions after alarm thresholds are crossed).
:param alarm_id: ID of alarm to return changes for
:param on_behalf_of: ID of tenant to scope changes query (None for
administrative user, indicating all projects)
:param user: Optional ID of user to return changes for
:param project: Optional ID of project to return changes for
:param alarm_type: Optional change type
:param severity: Optional change severity
:param start_timestamp: Optional modified timestamp start range
:param start_timestamp_op: Optional timestamp start range operation
:param end_timestamp: Optional modified timestamp end range
:param end_timestamp_op: Optional timestamp end range operation<|endoftext|> |
48e31ce79772beb45a9c4079d7f02a802037d65e5c68ebcd4dba755d1c334059 | def query_alarms(self, filter_expr=None, orderby=None, limit=None):
'Return an iterable of model.Alarm objects.'
return self._retrieve_data(filter_expr, orderby, limit, models.Alarm) | Return an iterable of model.Alarm objects. | ceilometer/alarm/storage/pymongo_base.py | query_alarms | glove747/liberty-ceilometer | 1 | python | def query_alarms(self, filter_expr=None, orderby=None, limit=None):
return self._retrieve_data(filter_expr, orderby, limit, models.Alarm) | def query_alarms(self, filter_expr=None, orderby=None, limit=None):
return self._retrieve_data(filter_expr, orderby, limit, models.Alarm)<|docstring|>Return an iterable of model.Alarm objects.<|endoftext|> |
9e41847abece912bfd6db5af3f0579f447140fcdab663a02b847660cefdf41c9 | def query_alarm_history(self, filter_expr=None, orderby=None, limit=None):
'Return an iterable of model.AlarmChange objects.'
return self._retrieve_data(filter_expr, orderby, limit, models.AlarmChange) | Return an iterable of model.AlarmChange objects. | ceilometer/alarm/storage/pymongo_base.py | query_alarm_history | glove747/liberty-ceilometer | 1 | python | def query_alarm_history(self, filter_expr=None, orderby=None, limit=None):
return self._retrieve_data(filter_expr, orderby, limit, models.AlarmChange) | def query_alarm_history(self, filter_expr=None, orderby=None, limit=None):
return self._retrieve_data(filter_expr, orderby, limit, models.AlarmChange)<|docstring|>Return an iterable of model.AlarmChange objects.<|endoftext|> |
c85becd802b4b293a921676f1f7a90c5c136a57bd1300f7582bbb0f689755af2 | @classmethod
def _ensure_encapsulated_rule_format(cls, alarm):
'Ensure the alarm returned by the storage have the correct format.\n\n The previous format looks like:\n {\n \'alarm_id\': \'0ld-4l3rt\',\n \'enabled\': True,\n \'name\': \'old-alert\',\n \'description\': \'old-alert\',\n \'timestamp\': None,\n \'meter_name\': \'cpu\',\n \'user_id\': \'me\',\n \'project_id\': \'and-da-boys\',\n \'comparison_operator\': \'lt\',\n \'threshold\': 36,\n \'statistic\': \'count\',\n \'evaluation_periods\': 1,\n \'period\': 60,\n \'state\': "insufficient data",\n \'state_timestamp\': None,\n \'ok_actions\': [],\n \'alarm_actions\': [\'http://nowhere/alarms\'],\n \'insufficient_data_actions\': [],\n \'repeat_actions\': False,\n \'matching_metadata\': {\'key\': \'value\'}\n # or \'matching_metadata\': [{\'key\': \'key\', \'value\': \'value\'}]\n }\n '
if isinstance(alarm.get('rule'), dict):
return
alarm['type'] = 'threshold'
alarm['rule'] = {}
alarm['matching_metadata'] = cls._decode_matching_metadata(alarm['matching_metadata'])
for field in ['period', 'evaluation_periods', 'threshold', 'statistic', 'comparison_operator', 'meter_name']:
if (field in alarm):
alarm['rule'][field] = alarm[field]
del alarm[field]
query = []
for key in alarm['matching_metadata']:
query.append({'field': key, 'op': 'eq', 'value': alarm['matching_metadata'][key], 'type': 'string'})
del alarm['matching_metadata']
alarm['rule']['query'] = query | Ensure the alarm returned by the storage have the correct format.
The previous format looks like:
{
'alarm_id': '0ld-4l3rt',
'enabled': True,
'name': 'old-alert',
'description': 'old-alert',
'timestamp': None,
'meter_name': 'cpu',
'user_id': 'me',
'project_id': 'and-da-boys',
'comparison_operator': 'lt',
'threshold': 36,
'statistic': 'count',
'evaluation_periods': 1,
'period': 60,
'state': "insufficient data",
'state_timestamp': None,
'ok_actions': [],
'alarm_actions': ['http://nowhere/alarms'],
'insufficient_data_actions': [],
'repeat_actions': False,
'matching_metadata': {'key': 'value'}
# or 'matching_metadata': [{'key': 'key', 'value': 'value'}]
} | ceilometer/alarm/storage/pymongo_base.py | _ensure_encapsulated_rule_format | glove747/liberty-ceilometer | 1 | python | @classmethod
def _ensure_encapsulated_rule_format(cls, alarm):
'Ensure the alarm returned by the storage have the correct format.\n\n The previous format looks like:\n {\n \'alarm_id\': \'0ld-4l3rt\',\n \'enabled\': True,\n \'name\': \'old-alert\',\n \'description\': \'old-alert\',\n \'timestamp\': None,\n \'meter_name\': \'cpu\',\n \'user_id\': \'me\',\n \'project_id\': \'and-da-boys\',\n \'comparison_operator\': \'lt\',\n \'threshold\': 36,\n \'statistic\': \'count\',\n \'evaluation_periods\': 1,\n \'period\': 60,\n \'state\': "insufficient data",\n \'state_timestamp\': None,\n \'ok_actions\': [],\n \'alarm_actions\': [\'http://nowhere/alarms\'],\n \'insufficient_data_actions\': [],\n \'repeat_actions\': False,\n \'matching_metadata\': {\'key\': \'value\'}\n # or \'matching_metadata\': [{\'key\': \'key\', \'value\': \'value\'}]\n }\n '
if isinstance(alarm.get('rule'), dict):
return
alarm['type'] = 'threshold'
alarm['rule'] = {}
alarm['matching_metadata'] = cls._decode_matching_metadata(alarm['matching_metadata'])
for field in ['period', 'evaluation_periods', 'threshold', 'statistic', 'comparison_operator', 'meter_name']:
if (field in alarm):
alarm['rule'][field] = alarm[field]
del alarm[field]
query = []
for key in alarm['matching_metadata']:
query.append({'field': key, 'op': 'eq', 'value': alarm['matching_metadata'][key], 'type': 'string'})
del alarm['matching_metadata']
alarm['rule']['query'] = query | @classmethod
def _ensure_encapsulated_rule_format(cls, alarm):
'Ensure the alarm returned by the storage have the correct format.\n\n The previous format looks like:\n {\n \'alarm_id\': \'0ld-4l3rt\',\n \'enabled\': True,\n \'name\': \'old-alert\',\n \'description\': \'old-alert\',\n \'timestamp\': None,\n \'meter_name\': \'cpu\',\n \'user_id\': \'me\',\n \'project_id\': \'and-da-boys\',\n \'comparison_operator\': \'lt\',\n \'threshold\': 36,\n \'statistic\': \'count\',\n \'evaluation_periods\': 1,\n \'period\': 60,\n \'state\': "insufficient data",\n \'state_timestamp\': None,\n \'ok_actions\': [],\n \'alarm_actions\': [\'http://nowhere/alarms\'],\n \'insufficient_data_actions\': [],\n \'repeat_actions\': False,\n \'matching_metadata\': {\'key\': \'value\'}\n # or \'matching_metadata\': [{\'key\': \'key\', \'value\': \'value\'}]\n }\n '
if isinstance(alarm.get('rule'), dict):
return
alarm['type'] = 'threshold'
alarm['rule'] = {}
alarm['matching_metadata'] = cls._decode_matching_metadata(alarm['matching_metadata'])
for field in ['period', 'evaluation_periods', 'threshold', 'statistic', 'comparison_operator', 'meter_name']:
if (field in alarm):
alarm['rule'][field] = alarm[field]
del alarm[field]
query = []
for key in alarm['matching_metadata']:
query.append({'field': key, 'op': 'eq', 'value': alarm['matching_metadata'][key], 'type': 'string'})
del alarm['matching_metadata']
alarm['rule']['query'] = query<|docstring|>Ensure the alarm returned by the storage have the correct format.
The previous format looks like:
{
'alarm_id': '0ld-4l3rt',
'enabled': True,
'name': 'old-alert',
'description': 'old-alert',
'timestamp': None,
'meter_name': 'cpu',
'user_id': 'me',
'project_id': 'and-da-boys',
'comparison_operator': 'lt',
'threshold': 36,
'statistic': 'count',
'evaluation_periods': 1,
'period': 60,
'state': "insufficient data",
'state_timestamp': None,
'ok_actions': [],
'alarm_actions': ['http://nowhere/alarms'],
'insufficient_data_actions': [],
'repeat_actions': False,
'matching_metadata': {'key': 'value'}
# or 'matching_metadata': [{'key': 'key', 'value': 'value'}]
}<|endoftext|> |
4bfd3f6ce689b7267610c2f7ff0898f2b4db6b720e90fea7fe8739224e2f8e35 | @staticmethod
def _ensure_time_constraints(alarm):
'Ensures the alarm has a time constraints field.'
if ('time_constraints' not in alarm):
alarm['time_constraints'] = [] | Ensures the alarm has a time constraints field. | ceilometer/alarm/storage/pymongo_base.py | _ensure_time_constraints | glove747/liberty-ceilometer | 1 | python | @staticmethod
def _ensure_time_constraints(alarm):
if ('time_constraints' not in alarm):
alarm['time_constraints'] = [] | @staticmethod
def _ensure_time_constraints(alarm):
if ('time_constraints' not in alarm):
alarm['time_constraints'] = []<|docstring|>Ensures the alarm has a time constraints field.<|endoftext|> |
c113db665bd2b90bcab4209894a0823d415bd14cbfa0ca6fa6a076d6f153d6d5 | def remove_current_translations():
'\n Remove current translations, as well as temporary files that might be left behind\n We only want the active translations that are currently on transifex.\n This leaves pivx_en.ts untouched.\n '
for (_, name) in all_ts_files():
os.remove(name)
for (_, name) in all_ts_files('.orig'):
os.remove((name + '.orig')) | Remove current translations, as well as temporary files that might be left behind
We only want the active translations that are currently on transifex.
This leaves pivx_en.ts untouched. | contrib/devtools/update-translations.py | remove_current_translations | luckycoinblu/LuckyCoinBlu | 638 | python | def remove_current_translations():
'\n Remove current translations, as well as temporary files that might be left behind\n We only want the active translations that are currently on transifex.\n This leaves pivx_en.ts untouched.\n '
for (_, name) in all_ts_files():
os.remove(name)
for (_, name) in all_ts_files('.orig'):
os.remove((name + '.orig')) | def remove_current_translations():
'\n Remove current translations, as well as temporary files that might be left behind\n We only want the active translations that are currently on transifex.\n This leaves pivx_en.ts untouched.\n '
for (_, name) in all_ts_files():
os.remove(name)
for (_, name) in all_ts_files('.orig'):
os.remove((name + '.orig'))<|docstring|>Remove current translations, as well as temporary files that might be left behind
We only want the active translations that are currently on transifex.
This leaves pivx_en.ts untouched.<|endoftext|> |
4f5f6076fd4f119c5a29834ff75729ce39b86a73c1c631f220c36c707ff1d7d0 | def find_format_specifiers(s):
'Find all format specifiers in a string.'
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if (percent < 0):
break
try:
specifiers.append(s[(percent + 1)])
except:
print('Failed to get specifier')
pos = (percent + 2)
return specifiers | Find all format specifiers in a string. | contrib/devtools/update-translations.py | find_format_specifiers | luckycoinblu/LuckyCoinBlu | 638 | python | def find_format_specifiers(s):
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if (percent < 0):
break
try:
specifiers.append(s[(percent + 1)])
except:
print('Failed to get specifier')
pos = (percent + 2)
return specifiers | def find_format_specifiers(s):
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if (percent < 0):
break
try:
specifiers.append(s[(percent + 1)])
except:
print('Failed to get specifier')
pos = (percent + 2)
return specifiers<|docstring|>Find all format specifiers in a string.<|endoftext|> |
080ae80b70c67550ea40b5be187c8a4514dd2b13aa1acf022e6db3da5028e055 | def split_format_specifiers(specifiers):
'Split format specifiers between numeric (Qt) and others (strprintf)'
numeric = []
other = []
for s in specifiers:
if (s in {'1', '2', '3', '4', '5', '6', '7', '8', '9'}):
numeric.append(s)
else:
other.append(s)
if numeric:
other = []
return (set(numeric), other) | Split format specifiers between numeric (Qt) and others (strprintf) | contrib/devtools/update-translations.py | split_format_specifiers | luckycoinblu/LuckyCoinBlu | 638 | python | def split_format_specifiers(specifiers):
numeric = []
other = []
for s in specifiers:
if (s in {'1', '2', '3', '4', '5', '6', '7', '8', '9'}):
numeric.append(s)
else:
other.append(s)
if numeric:
other = []
return (set(numeric), other) | def split_format_specifiers(specifiers):
numeric = []
other = []
for s in specifiers:
if (s in {'1', '2', '3', '4', '5', '6', '7', '8', '9'}):
numeric.append(s)
else:
other.append(s)
if numeric:
other = []
return (set(numeric), other)<|docstring|>Split format specifiers between numeric (Qt) and others (strprintf)<|endoftext|> |
50e82db9556b68fe812a33d4b1cc99e77a62a7be1b8f11164383762ab4ade912 | def sanitize_string(s):
'Sanitize string for printing'
return s.replace('\n', ' ') | Sanitize string for printing | contrib/devtools/update-translations.py | sanitize_string | luckycoinblu/LuckyCoinBlu | 638 | python | def sanitize_string(s):
return s.replace('\n', ' ') | def sanitize_string(s):
return s.replace('\n', ' ')<|docstring|>Sanitize string for printing<|endoftext|> |
4f4731cd4c814d5fd3d235da26fef000ac96793d4ef795fba9bce278a8b72c4c | def remove_invalid_characters(s):
'Remove invalid characters from translation string'
return FIX_RE.sub(b'', s) | Remove invalid characters from translation string | contrib/devtools/update-translations.py | remove_invalid_characters | luckycoinblu/LuckyCoinBlu | 638 | python | def remove_invalid_characters(s):
return FIX_RE.sub(b, s) | def remove_invalid_characters(s):
return FIX_RE.sub(b, s)<|docstring|>Remove invalid characters from translation string<|endoftext|> |
bee33722ff8e5f1b956a15f9cc8b5c744246cc3e77019458b1a87ca7c07e26ec | def update_git():
"\n Add new files to git repository.\n (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone)\n "
file_paths = [filepath for (filename, filepath) in all_ts_files()]
subprocess.check_call(([GIT, 'add'] + file_paths)) | Add new files to git repository.
(Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone) | contrib/devtools/update-translations.py | update_git | luckycoinblu/LuckyCoinBlu | 638 | python | def update_git():
"\n Add new files to git repository.\n (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone)\n "
file_paths = [filepath for (filename, filepath) in all_ts_files()]
subprocess.check_call(([GIT, 'add'] + file_paths)) | def update_git():
"\n Add new files to git repository.\n (Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone)\n "
file_paths = [filepath for (filename, filepath) in all_ts_files()]
subprocess.check_call(([GIT, 'add'] + file_paths))<|docstring|>Add new files to git repository.
(Removing files isn't necessary here, as `git commit -a` will take care of removing files that are gone)<|endoftext|> |
cd892962107570de7bddf7b714bbcebdc3f5a02ae3d512bb226a3f89e3a10add | def update_build_systems():
'\n Update build system and Qt resource descriptors.\n '
filename_lang = [re.match('((pivx_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)]
filename_lang.sort(key=(lambda x: x[0]))
with open('src/qt/pivx_locale.qrc', 'w', encoding='utf8') as f:
f.write('<!DOCTYPE RCC><RCC version="1.0">\n')
f.write(' <qresource prefix="/translations">\n')
for (filename, basename, lang) in filename_lang:
f.write(f''' <file alias="{lang}">locale/{basename}.qm</file>
''')
f.write(' </qresource>\n')
f.write('</RCC>\n')
with open('src/Makefile.qt_locale.include', 'w', encoding='utf8') as f:
f.write('QT_TS = \\\n')
f.write(' \\\n'.join((f' qt/locale/{filename}' for (filename, basename, lang) in filename_lang)))
f.write('\n') | Update build system and Qt resource descriptors. | contrib/devtools/update-translations.py | update_build_systems | luckycoinblu/LuckyCoinBlu | 638 | python | def update_build_systems():
'\n \n '
filename_lang = [re.match('((pivx_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)]
filename_lang.sort(key=(lambda x: x[0]))
with open('src/qt/pivx_locale.qrc', 'w', encoding='utf8') as f:
f.write('<!DOCTYPE RCC><RCC version="1.0">\n')
f.write(' <qresource prefix="/translations">\n')
for (filename, basename, lang) in filename_lang:
f.write(f' <file alias="{lang}">locale/{basename}.qm</file>
')
f.write(' </qresource>\n')
f.write('</RCC>\n')
with open('src/Makefile.qt_locale.include', 'w', encoding='utf8') as f:
f.write('QT_TS = \\\n')
f.write(' \\\n'.join((f' qt/locale/{filename}' for (filename, basename, lang) in filename_lang)))
f.write('\n') | def update_build_systems():
'\n \n '
filename_lang = [re.match('((pivx_(.*)).ts)$', filename).groups() for (filename, filepath) in all_ts_files(include_source=True)]
filename_lang.sort(key=(lambda x: x[0]))
with open('src/qt/pivx_locale.qrc', 'w', encoding='utf8') as f:
f.write('<!DOCTYPE RCC><RCC version="1.0">\n')
f.write(' <qresource prefix="/translations">\n')
for (filename, basename, lang) in filename_lang:
f.write(f' <file alias="{lang}">locale/{basename}.qm</file>
')
f.write(' </qresource>\n')
f.write('</RCC>\n')
with open('src/Makefile.qt_locale.include', 'w', encoding='utf8') as f:
f.write('QT_TS = \\\n')
f.write(' \\\n'.join((f' qt/locale/{filename}' for (filename, basename, lang) in filename_lang)))
f.write('\n')<|docstring|>Update build system and Qt resource descriptors.<|endoftext|> |
ab4925081639c89c0d635fe274ba4cdc7bba4a59e436235a6b678cfa02df17e0 | def create_session(self, access_key, secret_key, session_token=None):
'\n Create a session to AWS using the credentials provided.\n If no credentials are provided then, credentials are read from aws_config.json file.\n\n :param access_key: access key for the IAM user\n :param secret_key: secret key for the IAM user\n :param access_token:\n '
try:
if session_token:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token)
else:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
except Exception as e:
self.logger.error(e) | Create a session to AWS using the credentials provided.
If no credentials are provided then, credentials are read from aws_config.json file.
:param access_key: access key for the IAM user
:param secret_key: secret key for the IAM user
:param access_token: | lib/awsLib/S3.py | create_session | umang-cb/TAF | 9 | python | def create_session(self, access_key, secret_key, session_token=None):
'\n Create a session to AWS using the credentials provided.\n If no credentials are provided then, credentials are read from aws_config.json file.\n\n :param access_key: access key for the IAM user\n :param secret_key: secret key for the IAM user\n :param access_token:\n '
try:
if session_token:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token)
else:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
except Exception as e:
self.logger.error(e) | def create_session(self, access_key, secret_key, session_token=None):
'\n Create a session to AWS using the credentials provided.\n If no credentials are provided then, credentials are read from aws_config.json file.\n\n :param access_key: access key for the IAM user\n :param secret_key: secret key for the IAM user\n :param access_token:\n '
try:
if session_token:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token)
else:
self.aws_session = boto3.Session(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
except Exception as e:
self.logger.error(e)<|docstring|>Create a session to AWS using the credentials provided.
If no credentials are provided then, credentials are read from aws_config.json file.
:param access_key: access key for the IAM user
:param secret_key: secret key for the IAM user
:param access_token:<|endoftext|> |
2d00b694255344a0fe50003e3dc1d4eb0412ce9866d46965199fbc36351fee02 | def create_service_client(self, service_name, region=None):
'\n Create a low level client for the service specified.\n If a region is not specified, the client is created in the default region (us-east-1).\n :param service_name: name of the service for which the client has to be created\n :param region: region in which the client has to created.\n '
try:
if (region is None):
return self.aws_session.client(service_name)
else:
return self.aws_session.client(service_name, region_name=region)
except ClientError as e:
self.logger.error(e) | Create a low level client for the service specified.
If a region is not specified, the client is created in the default region (us-east-1).
:param service_name: name of the service for which the client has to be created
:param region: region in which the client has to created. | lib/awsLib/S3.py | create_service_client | umang-cb/TAF | 9 | python | def create_service_client(self, service_name, region=None):
'\n Create a low level client for the service specified.\n If a region is not specified, the client is created in the default region (us-east-1).\n :param service_name: name of the service for which the client has to be created\n :param region: region in which the client has to created.\n '
try:
if (region is None):
return self.aws_session.client(service_name)
else:
return self.aws_session.client(service_name, region_name=region)
except ClientError as e:
self.logger.error(e) | def create_service_client(self, service_name, region=None):
'\n Create a low level client for the service specified.\n If a region is not specified, the client is created in the default region (us-east-1).\n :param service_name: name of the service for which the client has to be created\n :param region: region in which the client has to created.\n '
try:
if (region is None):
return self.aws_session.client(service_name)
else:
return self.aws_session.client(service_name, region_name=region)
except ClientError as e:
self.logger.error(e)<|docstring|>Create a low level client for the service specified.
If a region is not specified, the client is created in the default region (us-east-1).
:param service_name: name of the service for which the client has to be created
:param region: region in which the client has to created.<|endoftext|> |
ecacc5b4959623e71d7a96a47b229413e3c4cecc5680b03e0bc0e49485e9f027 | def create_service_resource(self, resource_name):
'\n Create a service resource object, to access resources related to service.\n '
try:
return self.aws_session.resource(resource_name)
except Exception as e:
self.logger.error(e) | Create a service resource object, to access resources related to service. | lib/awsLib/S3.py | create_service_resource | umang-cb/TAF | 9 | python | def create_service_resource(self, resource_name):
'\n \n '
try:
return self.aws_session.resource(resource_name)
except Exception as e:
self.logger.error(e) | def create_service_resource(self, resource_name):
'\n \n '
try:
return self.aws_session.resource(resource_name)
except Exception as e:
self.logger.error(e)<|docstring|>Create a service resource object, to access resources related to service.<|endoftext|> |
b0e710b4ebd60d4dec934f27abe4859fb56c0af73a53635acf7a35a5b80f3f35 | def create_bucket(self, bucket_name, region):
"\n Create an S3 bucket in a specified region\n If a region is not specified, the bucket is created in the S3 default region (us-east-1).\n\n :param bucket_name: Bucket to create\n :param region: String region to create bucket in, e.g., 'us-west-2'\n :return: True if bucket created, else False\n "
try:
location = {'LocationConstraint': region}
response = self.s3_resource.Bucket(bucket_name).create(CreateBucketConfiguration=location)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False | Create an S3 bucket in a specified region
If a region is not specified, the bucket is created in the S3 default region (us-east-1).
:param bucket_name: Bucket to create
:param region: String region to create bucket in, e.g., 'us-west-2'
:return: True if bucket created, else False | lib/awsLib/S3.py | create_bucket | umang-cb/TAF | 9 | python | def create_bucket(self, bucket_name, region):
"\n Create an S3 bucket in a specified region\n If a region is not specified, the bucket is created in the S3 default region (us-east-1).\n\n :param bucket_name: Bucket to create\n :param region: String region to create bucket in, e.g., 'us-west-2'\n :return: True if bucket created, else False\n "
try:
location = {'LocationConstraint': region}
response = self.s3_resource.Bucket(bucket_name).create(CreateBucketConfiguration=location)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False | def create_bucket(self, bucket_name, region):
"\n Create an S3 bucket in a specified region\n If a region is not specified, the bucket is created in the S3 default region (us-east-1).\n\n :param bucket_name: Bucket to create\n :param region: String region to create bucket in, e.g., 'us-west-2'\n :return: True if bucket created, else False\n "
try:
location = {'LocationConstraint': region}
response = self.s3_resource.Bucket(bucket_name).create(CreateBucketConfiguration=location)
if (response['ResponseMetadata']['HTTPStatusCode'] == 200):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False<|docstring|>Create an S3 bucket in a specified region
If a region is not specified, the bucket is created in the S3 default region (us-east-1).
:param bucket_name: Bucket to create
:param region: String region to create bucket in, e.g., 'us-west-2'
:return: True if bucket created, else False<|endoftext|> |
dcc2865b589d6267bfed3c325c95234cf7905494965d29dab03ead1b3380f53d | def delete_bucket(self, bucket_name, max_retry=5, retry_attempt=0):
'\n Deletes a bucket\n :param bucket_name: Bucket to delete\n '
try:
bucket_deleted = False
if (retry_attempt < max_retry):
if self.empty_bucket(bucket_name):
response = self.s3_resource.Bucket(bucket_name).delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
bucket_deleted = True
if (not bucket_deleted):
self.delete_bucket(bucket_name, max_retry, (retry_attempt + 1))
else:
return bucket_deleted
else:
return False
except Exception as e:
self.logger.error(e)
return False | Deletes a bucket
:param bucket_name: Bucket to delete | lib/awsLib/S3.py | delete_bucket | umang-cb/TAF | 9 | python | def delete_bucket(self, bucket_name, max_retry=5, retry_attempt=0):
'\n Deletes a bucket\n :param bucket_name: Bucket to delete\n '
try:
bucket_deleted = False
if (retry_attempt < max_retry):
if self.empty_bucket(bucket_name):
response = self.s3_resource.Bucket(bucket_name).delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
bucket_deleted = True
if (not bucket_deleted):
self.delete_bucket(bucket_name, max_retry, (retry_attempt + 1))
else:
return bucket_deleted
else:
return False
except Exception as e:
self.logger.error(e)
return False | def delete_bucket(self, bucket_name, max_retry=5, retry_attempt=0):
'\n Deletes a bucket\n :param bucket_name: Bucket to delete\n '
try:
bucket_deleted = False
if (retry_attempt < max_retry):
if self.empty_bucket(bucket_name):
response = self.s3_resource.Bucket(bucket_name).delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
bucket_deleted = True
if (not bucket_deleted):
self.delete_bucket(bucket_name, max_retry, (retry_attempt + 1))
else:
return bucket_deleted
else:
return False
except Exception as e:
self.logger.error(e)
return False<|docstring|>Deletes a bucket
:param bucket_name: Bucket to delete<|endoftext|> |
a49cabc9f6cfd6a6c4b1009ea4b83c8e59597a837130cf53c85e52c853927b5d | def delete_file(self, bucket_name, file_path, version_id=None):
'\n Deletes a single file/object, identified by object name.\n :param bucket_name: Bucket whose objects are to be deleted.\n :param file_path: path of the file, relative to S3 bucket\n :param version_id: to delete a specific version of an object.\n '
try:
s3_object = self.s3_resource.Object(bucket_name, file_path)
if version_id:
response = s3_object.delete(VersionId=version_id)
else:
response = s3_object.delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False | Deletes a single file/object, identified by object name.
:param bucket_name: Bucket whose objects are to be deleted.
:param file_path: path of the file, relative to S3 bucket
:param version_id: to delete a specific version of an object. | lib/awsLib/S3.py | delete_file | umang-cb/TAF | 9 | python | def delete_file(self, bucket_name, file_path, version_id=None):
'\n Deletes a single file/object, identified by object name.\n :param bucket_name: Bucket whose objects are to be deleted.\n :param file_path: path of the file, relative to S3 bucket\n :param version_id: to delete a specific version of an object.\n '
try:
s3_object = self.s3_resource.Object(bucket_name, file_path)
if version_id:
response = s3_object.delete(VersionId=version_id)
else:
response = s3_object.delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False | def delete_file(self, bucket_name, file_path, version_id=None):
'\n Deletes a single file/object, identified by object name.\n :param bucket_name: Bucket whose objects are to be deleted.\n :param file_path: path of the file, relative to S3 bucket\n :param version_id: to delete a specific version of an object.\n '
try:
s3_object = self.s3_resource.Object(bucket_name, file_path)
if version_id:
response = s3_object.delete(VersionId=version_id)
else:
response = s3_object.delete()
if (response['ResponseMetadata']['HTTPStatusCode'] == 204):
return True
else:
return False
except Exception as e:
self.logger.error(e)
return False<|docstring|>Deletes a single file/object, identified by object name.
:param bucket_name: Bucket whose objects are to be deleted.
:param file_path: path of the file, relative to S3 bucket
:param version_id: to delete a specific version of an object.<|endoftext|> |
cc5d5971eba14bf661e33aa240e5367f0fc0ee2a320b7bdd005c740b3cd72409 | def empty_bucket(self, bucket_name):
'\n Deletes all the objects in the bucket.\n :param bucket_name: Bucket whose objects are to be deleted.\n '
try:
response = self.s3_resource.BucketVersioning(bucket_name).status
if (not response):
versioning = True
else:
versioning = False
bucket_resource = self.s3_resource.Bucket(bucket_name)
if versioning:
response = bucket_resource.object_versions.all().delete()
else:
response = bucket_resource.objects.all().delete()
status = True
for item in response:
if (item['ResponseMetadata']['HTTPStatusCode'] != 200):
status = (status and False)
return status
except Exception as e:
self.logger.error(e)
return False | Deletes all the objects in the bucket.
:param bucket_name: Bucket whose objects are to be deleted. | lib/awsLib/S3.py | empty_bucket | umang-cb/TAF | 9 | python | def empty_bucket(self, bucket_name):
'\n Deletes all the objects in the bucket.\n :param bucket_name: Bucket whose objects are to be deleted.\n '
try:
response = self.s3_resource.BucketVersioning(bucket_name).status
if (not response):
versioning = True
else:
versioning = False
bucket_resource = self.s3_resource.Bucket(bucket_name)
if versioning:
response = bucket_resource.object_versions.all().delete()
else:
response = bucket_resource.objects.all().delete()
status = True
for item in response:
if (item['ResponseMetadata']['HTTPStatusCode'] != 200):
status = (status and False)
return status
except Exception as e:
self.logger.error(e)
return False | def empty_bucket(self, bucket_name):
'\n Deletes all the objects in the bucket.\n :param bucket_name: Bucket whose objects are to be deleted.\n '
try:
response = self.s3_resource.BucketVersioning(bucket_name).status
if (not response):
versioning = True
else:
versioning = False
bucket_resource = self.s3_resource.Bucket(bucket_name)
if versioning:
response = bucket_resource.object_versions.all().delete()
else:
response = bucket_resource.objects.all().delete()
status = True
for item in response:
if (item['ResponseMetadata']['HTTPStatusCode'] != 200):
status = (status and False)
return status
except Exception as e:
self.logger.error(e)
return False<|docstring|>Deletes all the objects in the bucket.
:param bucket_name: Bucket whose objects are to be deleted.<|endoftext|> |
98c88f20c3a42e1dcad3db30d79e09cbcd71d6cd95db55dd8dbf163655db19ff | def list_existing_buckets(self):
'\n List all the S3 buckets.\n '
try:
response = self.s3_client.list_buckets()
if response:
return [x['Name'] for x in response['Buckets']]
else:
return []
except Exception as e:
self.logger.error(e)
return [] | List all the S3 buckets. | lib/awsLib/S3.py | list_existing_buckets | umang-cb/TAF | 9 | python | def list_existing_buckets(self):
'\n \n '
try:
response = self.s3_client.list_buckets()
if response:
return [x['Name'] for x in response['Buckets']]
else:
return []
except Exception as e:
self.logger.error(e)
return [] | def list_existing_buckets(self):
'\n \n '
try:
response = self.s3_client.list_buckets()
if response:
return [x['Name'] for x in response['Buckets']]
else:
return []
except Exception as e:
self.logger.error(e)
return []<|docstring|>List all the S3 buckets.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.