def run_in_separate_process(func, *args, **kwargs):

manager = multiprocessing.Manager()<EOL>manager_dict = manager.dict()<EOL>process = ProcessWithException(<EOL>manager_dict, target=func, args=args, kwargs=kwargs)<EOL>process.start()<EOL>process.join()<EOL>exc = process.exception<EOL>if exc:<EOL><INDENT>raise exc<EOL><DEDENT>return process.output<EOL>

Runs function in separate process.

    This function is used instead of a decorator, since Python multiprocessing
    module can't serialize decorated function on all platforms.


run_obj_type = self.get_run_object_type(run_object)<EOL>if run_obj_type == '<STR_LIT>':<EOL><INDENT>self.init_module(run_object)<EOL><DEDENT>elif run_obj_type == '<STR_LIT>':<EOL><INDENT>self.init_package(run_object)<EOL><DEDENT>else:<EOL><INDENT>self.init_function(run_object)<EOL><DEDENT>

Initializes profiler.

        Args:
            run_object: object to be profiled.


def run_profilers(run_object, prof_config, verbose=False):

if len(prof_config) > len(set(prof_config)):<EOL><INDENT>raise AmbiguousConfigurationError(<EOL>'<STR_LIT>' % prof_config)<EOL><DEDENT>available_profilers = {opt for opt, _ in _PROFILERS}<EOL>for option in prof_config:<EOL><INDENT>if option not in available_profilers:<EOL><INDENT>raise BadOptionError('<STR_LIT>' % option)<EOL><DEDENT><DEDENT>run_stats = OrderedDict()<EOL>present_profilers = ((o, p) for o, p in _PROFILERS if o in prof_config)<EOL>for option, prof in present_profilers:<EOL><INDENT>curr_profiler = prof(run_object)<EOL>if verbose:<EOL><INDENT>print('<STR_LIT>' % curr_profiler.__class__.__name__)<EOL><DEDENT>run_stats[option] = curr_profiler.run()<EOL><DEDENT>return run_stats<EOL>

Runs profilers on run_object.

    Args:
        run_object: An object (string or tuple) for profiling.
        prof_config: A string with profilers configuration.
        verbose: True if info about running profilers should be shown.
    Returns:
        An ordered dictionary with collected stats.
    Raises:
        AmbiguousConfigurationError: when prof_config is ambiguous.
        BadOptionError: when unknown options are present in configuration.


@app.route('<STR_LIT>', methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>def profiler_handler(uri):

<EOL>if uri == '<STR_LIT>':<EOL><INDENT>runner.run(show_guestbook, '<STR_LIT>')<EOL><DEDENT>elif uri == '<STR_LIT>':<EOL><INDENT>runner.run(add_entry, '<STR_LIT>')<EOL><DEDENT>return flask.redirect('<STR_LIT:/>')<EOL>


name, msg = flask.request.form['<STR_LIT:name>'], flask.request.form['<STR_LIT:message>']<EOL>flask.g.db.execute(<EOL>'<STR_LIT>', (name, msg))<EOL>flask.g.db.commit()<EOL>return flask.redirect('<STR_LIT:/>')<EOL>


return sqlite3.connect(DB)<EOL>


with contextlib.closing(connect_to_db()) as db:<EOL><INDENT>db.cursor().executescript(DB_SCHEMA)<EOL>db.commit()<EOL><DEDENT>


cursor = flask.g.db.execute(<EOL>'<STR_LIT>')<EOL>entries = [{'<STR_LIT:name>': row[<NUM_LIT:0>], '<STR_LIT:message>': row[<NUM_LIT:1>]} for row in cursor.fetchall()]<EOL>return jinja2.Template(LAYOUT).render(entries=entries)<EOL>


with open('<STR_LIT>') as readme_file:<EOL><INDENT>return readme_file.read()<EOL><DEDENT>


while True:<EOL><INDENT>pair = _random_adjspecies_pair()<EOL>if maxlen and len('<STR_LIT>'.join(pair)) > maxlen:<EOL><INDENT>continue<EOL><DEDENT>if prevent_stutter and pair[<NUM_LIT:0>][-<NUM_LIT:1>] == pair[<NUM_LIT:1>][<NUM_LIT:0>]:<EOL><INDENT>continue<EOL><DEDENT>return pair<EOL><DEDENT>

Return an ordered 2-tuple containing a species and a describer.
The letter-count of the pair is guarantee to not exceed `maxlen` if
it is given. If `prevent_stutter` is True, the last letter of the
first item of the pair will be different from the first letter of
the second item.


return choice(get_describers())<EOL>

Return a 2-tuple, matching a describer to 'prefix' or 'suffix'.


def random_adjspecies(sep='<STR_LIT>', maxlen=<NUM_LIT:8>, prevent_stutter=True):

pair = random_adjspecies_pair(maxlen, prevent_stutter)<EOL>return pair[<NUM_LIT:0>] + sep + pair[<NUM_LIT:1>]<EOL>

Return a random adjective/species, separated by `sep`. The keyword
arguments `maxlen` and `prevent_stutter` are the same as for
`random_adjspecies_pair`, but note that the maximum length argument is
not affected by the separator.


return choice(get_file_lines('<STR_LIT>'))<EOL>


file_path = path.join(path.dirname(path.abspath(__file__)), file_name)<EOL>with open(file_path) as file_obj:<EOL><INDENT>return [line for line in file_obj.read().splitlines() if line]<EOL><DEDENT>

Return a list of non-empty lines from `file_path`.


data = loadtxt(file_name, delimiter='<STR_LIT:=>', dtype=scipy.string0)<EOL>data_dict = dict(data)<EOL>for key in data_dict.keys():<EOL><INDENT>data_dict[key] = data_dict[key].strip()<EOL>data_dict[key.strip()] = data_dict[key]<EOL>del data_dict[key]<EOL><DEDENT>return data_dict<EOL>

Loads a text file to a python dictionary using '=' as the delimiter

        :param file_name: the name and path of the text file


done = False<EOL>dir_list = []<EOL>tic = time.clock()<EOL>lg.info('<STR_LIT>' + str(tic))<EOL>if self.run_params.num_cpus == -<NUM_LIT:1>:  <EOL><INDENT>self.run_params.num_cpus = os.sysconf("<STR_LIT>")<EOL>lg.info('<STR_LIT>' + str(self.run_params.num_cpus) + '<STR_LIT>')<EOL><DEDENT>tmp_dir_list = os.listdir(self.batch_output)<EOL>for direc in tmp_dir_list:<EOL><INDENT>dir_list.append(os.path.join(self.batch_output, direc))<EOL><DEDENT>num_dirs = len(dir_list)<EOL>lg.info('<STR_LIT>' + str(num_dirs) + '<STR_LIT>' + self.batch_output)<EOL>sub = scipy.floor(num_dirs / self.run_params.num_cpus)<EOL>remainder = num_dirs - (sub * self.run_params.num_cpus)<EOL>if remainder > <NUM_LIT:0>:<EOL><INDENT>lg.warning('<STR_LIT>')<EOL>lg.warning('<STR_LIT>')<EOL>lg.warning('<STR_LIT>' + str(remainder))<EOL><DEDENT>while not done:<EOL><INDENT>for l in range(<NUM_LIT:0>, int(sub)):<EOL><INDENT>lg.info('<STR_LIT>' + str(self.run_params.num_cpus) + '<STR_LIT>')<EOL>for m in range(<NUM_LIT:0>, self.run_params.num_cpus):<EOL><INDENT>_dir = dir_list.pop()<EOL>report_dir, report_file_name = os.path.split(self.run_params.report_file)<EOL>lg.debug(report_file_name)<EOL>lg.debug(os.path.join(_dir, report_file_name))<EOL>try:<EOL><INDENT>rep_size = os.path.getsize(os.path.join(_dir, report_file_name.strip('<STR_LIT:\n>')))<EOL>lg.debug('<STR_LIT>' + str(rep_size))<EOL><DEDENT>except:<EOL><INDENT>rep_size = <NUM_LIT:0><EOL><DEDENT>if rep_size < <NUM_LIT:1.0>:  <EOL><INDENT>lg.info('<STR_LIT>')<EOL>p = Process(target=self._run, args=(_dir,))<EOL><DEDENT>else:<EOL><INDENT>lg.warning('<STR_LIT>' + os.path.join(_dir, report_file_name.strip(<EOL>'<STR_LIT:\n>')) + '<STR_LIT>')<EOL>p = Process(target=self._dummy, args=(_dir,))<EOL><DEDENT>p.start()<EOL>lg.info('<STR_LIT>' + str(p.pid))<EOL><DEDENT>p.join()<EOL><DEDENT>self.run_params.num_cpus = remainder<EOL>remainder = <NUM_LIT:0><EOL>lg.info('<STR_LIT>')<EOL>sub = <NUM_LIT:1><EOL>if remainder == <NUM_LIT:0>:<EOL><INDENT>done = True<EOL><DEDENT><DEDENT>toc = time.clock()  <EOL>lg.info('<STR_LIT>' + str(toc))<EOL>timeTaken = toc - tic<EOL>lg.info('<STR_LIT>' + str(timeTaken))<EOL>

Distributes the work across the CPUs.  It actually uses _run()


inp_file = self.water_surface_file + '<STR_LIT>'<EOL>lg.info('<STR_LIT>' + inp_file)<EOL>if self.surf_state == '<STR_LIT>':  <EOL><INDENT>lg.info('<STR_LIT>')<EOL>f = open(inp_file, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' + str(self.verbose) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.num_bands) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(wave) for wave in self.wavelengths]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.partition + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.vn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.hn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(theta) for theta in self.theta_points]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.iface_type + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.iface_0_ri) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.iface_1_ri) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.wind_speed) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.wind_direc) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.crosswind_vertices) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.upwind_vertices) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.surface_size) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.surface_radius) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.target_size) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.rays_per_quad) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.surface_count) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.azimuthally_average) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + inp_file.strip('<STR_LIT>') + '<STR_LIT:\n>')<EOL>f.flush()<EOL>f.close()<EOL><DEDENT>

Write the params to file that surftool_Free needs to generate the surface facets


lg.info('<STR_LIT>' + str(scattering_fraction))<EOL>self.b = (self.b_b + self.b_water / <NUM_LIT>) / scattering_fraction<EOL>

Calculates the total scattering from back-scattering

        :param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833

        b = ( bb[sea water] + bb[p] ) /0.01833


inp_file = self.sky_file + '<STR_LIT>'<EOL>lg.info('<STR_LIT>' + inp_file)<EOL>f = open(inp_file, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' + str(self.verbose) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.num_bands) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(wave) for wave in self.wavelengths]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.partition + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.vn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.hn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.sky_r_dif) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(theta) for theta in self.theta_points]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.sky_type + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.sky_azimuth) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.sky_zenith) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + inp_file.strip('<STR_LIT>') + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.sky_file + '<STR_LIT>' + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + '<STR_LIT:\n>')<EOL>if self.sky_type == '<STR_LIT>':<EOL><INDENT>f.write('<STR_LIT>' + str(self.sky_c) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.sky_r_dif) + '<STR_LIT:\n>')<EOL><DEDENT>f.flush()<EOL>f.close()<EOL>

Writes the params to file that skytool_Free needs to generate the sky radiance distribution.


self.wavelengths = scipy.asarray([wavelengths])<EOL>self.b_bp = scipy.asarray([])<EOL>self.a_cdom = scipy.asarray([])<EOL>self.a_phi = scipy.asarray([])<EOL>self.a_water = scipy.asarray([])<EOL>self.b_water = scipy.asarray([])<EOL>self.b_b = scipy.asarray([])<EOL>self.b = scipy.asarray([])<EOL>self.a = scipy.asarray([])<EOL>self.c = scipy.asarray([])<EOL>

Constructor

        :param wavelengths: list of wavelengths all IOPs will be interpolated to


lg.info('<STR_LIT>' + file_name + '<STR_LIT>' + str(self.wavelengths))<EOL>if os.path.isfile(file_name):<EOL><INDENT>iop_reader = csv.reader(open(file_name), delimiter='<STR_LIT:U+002C>', quotechar='<STR_LIT:">')<EOL>wave = iop_reader.next()<EOL>iop = iop_reader.next()<EOL><DEDENT>else:<EOL><INDENT>lg.exception('<STR_LIT>' + file_name)<EOL>raise IOError<EOL><DEDENT>try:<EOL><INDENT>wave = map(float, wave)<EOL>iop = map(float, iop)<EOL>return scipy.interp(self.wavelengths, wave, iop)<EOL><DEDENT>except IOError:<EOL><INDENT>lg.exception('<STR_LIT>')<EOL>return -<NUM_LIT:1><EOL><DEDENT>

Generic IOP reader that interpolates the iop to the common wavelengths defined in the constructor

:param file_name: filename and path of the csv file
:returns interpolated iop


inp_file = os.path.join(os.path.join(self.input_path, '<STR_LIT>'), self.phase_function_file) + '<STR_LIT>'<EOL>lg.info('<STR_LIT>' + inp_file)<EOL>if self.iop_type == '<STR_LIT>' or '<STR_LIT>' or '<STR_LIT>' or '<STR_LIT>':<EOL><INDENT>lg.info('<STR_LIT>' + self.iop_type)<EOL>f = open(inp_file, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' + str(self.verbose) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.num_bands) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(wave) for wave in self.wavelengths]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.partition + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.vn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + str(self.hn) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>')<EOL>f.write("<STR_LIT:U+002C>".join([str(theta) for theta in self.theta_points]) + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + self.iop_type + '<STR_LIT:\n>')<EOL>f.write('<STR_LIT>' + inp_file.strip('<STR_LIT>') + '<STR_LIT:\n>')<EOL>f.flush()<EOL>f.close()<EOL><DEDENT>


data_object.__dict__ = data_dict<EOL>return data_object<EOL>

Maps a dictionary to an object.  Variable names become the key in the dict

        :param data_object: Is an instantiated class
        :param data_dict: is the python dictionary
        :returns data_object:


def display_graphic(self, flag_curves, ui):

ui.graphic_widget.canvas.picture.clear()<EOL>x = scipy.linspace(self.x_data[<NUM_LIT:0>], self.x_data[-<NUM_LIT:1>], len(self.x_data))  <EOL>curve_wanted = <NUM_LIT:0>  <EOL>for curve in self.y_data:<EOL><INDENT>if flag_curves:<EOL><INDENT>if curve_wanted == self.num_plot:  <EOL><INDENT>ui.graphic_widget.canvas.picture.plot(x, curve, '<STR_LIT>',<EOL>label='<STR_LIT>'.format(str(curve_wanted + <NUM_LIT:1>),<EOL>str(len(self.y_data))),<EOL>linewidth=<NUM_LIT:4>)<EOL><DEDENT>else:<EOL><INDENT>ui.graphic_widget.canvas.picture.plot(x, curve, '<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if curve_wanted == self.num_plot:<EOL><INDENT>ui.graphic_widget.canvas.picture.plot(x, curve, '<STR_LIT>',<EOL>label='<STR_LIT>'.format(str(curve_wanted + <NUM_LIT:1>),<EOL>str(len(self.y_data))))<EOL><DEDENT><DEDENT>curve_wanted += <NUM_LIT:1><EOL><DEDENT>ui.graphic_widget.canvas.picture.set_title('<STR_LIT>')<EOL>ui.graphic_widget.canvas.picture.set_xlabel('<STR_LIT>')<EOL>ui.graphic_widget.canvas.picture.set_ylabel('<STR_LIT>')<EOL>self.legend = ui.graphic_widget.canvas.picture.legend()  <EOL>ui.graphic_widget.canvas.picture.legend(bbox_to_anchor=(<NUM_LIT>, <NUM_LIT>))<EOL>ui.graphic_widget.canvas.draw()<EOL>

This function plots results of a file into the canvas.
Inputs : flag_curves : A boolean to know with we have to plot all curves or not.
         ui : The main_Window.


self.aboutWindow.show()<EOL>

This function opens the default browser and go on the web page about planarRad and its GUI.


bt = BatchFile(self.batch_name_value, self.p_values, self.x_value, self.y_value, self.g_value, self.s_value,<EOL>self.z_value, self.wavelength_values, self.verbose_value, self.phytoplankton_path,<EOL>self.bottom_path, self.nb_cpu, self.executive_path, self.saa_values,<EOL>self.sza_values, self.report_parameter_value)<EOL>bt.write_batch_to_file(str(self.batch_name_value + "<STR_LIT>"))<EOL>

This function calls "gui_batch.py" with inputs values to write the batch file.


def display_the_graphic(self, num_line, wavelength, data_wanted, information):

self.nb_case = num_line - <NUM_LIT:1>  <EOL>self.graphic_slider(self.nb_case)<EOL>self.mpl_canvas.update_fields(wavelength, data_wanted, self.slider_value)<EOL>if self.ui.show_grid.checkState() == <NUM_LIT:2>:<EOL><INDENT>grid = True<EOL><DEDENT>else:<EOL><INDENT>grid = False<EOL><DEDENT>if self.ui.show_all_curves.checkState() == <NUM_LIT:2>:<EOL><INDENT>self.flag_curves = True<EOL>self.mpl_canvas.display_graphic(self.flag_curves, self.ui, grid)<EOL>self.print_graphic_information(self.slider_value, information)<EOL><DEDENT>else:<EOL><INDENT>self.flag_curves = False<EOL>self.mpl_canvas.display_graphic(self.flag_curves, self.ui, grid)<EOL>self.print_graphic_information(self.slider_value, information)<EOL><DEDENT>

This function calls the class "MplCanvas" of "gui_matplotlibwidgetFile.py" to plot results.
Inputs : num_line : The number of cases.
         wavelength : The wavelengths.
         data_wanted : The data for wavelengths.
         information : The array which contains the information, of all curves to display.


menu = QtGui.QMenu()<EOL>self.actionSave_bis = menu.addAction("<STR_LIT>")<EOL>self.actionSave_as_bis = menu.addAction("<STR_LIT>")<EOL>action = menu.exec_(self.table_widget.mapFromGlobal(pos))<EOL>if action == self.actionSave_bis:<EOL><INDENT>self.save_figure()<EOL><DEDENT>elif action == self.actionSave_as_bis:<EOL><INDENT>self.save_figure_as()<EOL><DEDENT>

This function will open a context menu on the graphic to save it.
Inputs : pos : The position of the mouse cursor.


error_color = '<STR_LIT>'<EOL>no_error_color = '<STR_LIT>'  <EOL>self.error_batch_name = False<EOL>self.error_report_parameter = False<EOL>self.error_saa_result = False<EOL>self.error_sza_result = False<EOL>self.error_p_result = False<EOL>self.error_wavelength_result = False<EOL>self.error_x_result = False<EOL>self.error_y_result = False<EOL>self.error_g_result = False<EOL>self.error_s_result = False<EOL>self.error_z_result = False<EOL>self.error_verbose_result = False<EOL>self.error_phytoplankton_path_result = False<EOL>self.error_bottom_path_result = False<EOL>self.error_executive_path_result = False<EOL>"""<STR_LIT>"""<EOL>if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:<EOL><INDENT>check_num = '<STR_LIT>'  <EOL>self.prog = re.compile(check_num)  <EOL>batch_name_result = self.prog.search(<EOL>self.batch_name_value)  <EOL>report_parameter_result = self.prog.search(self.report_parameter_value)<EOL>try:<EOL><INDENT>if (self.ui.batch_name_value.text().isEmpty()) | (<EOL>batch_name_result.group() != self.ui.batch_name_value.text()):<EOL><INDENT>self.ui.batch_name_label.setStyleSheet(error_color)<EOL>self.error_batch_name = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.batch_name_label.setStyleSheet(no_error_color)<EOL>self.error_batch_name = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.batch_name_label.setStyleSheet(error_color)<EOL>self.error_batch_name = True<EOL><DEDENT>try:<EOL><INDENT>if (self.ui.report_parameter_value.text().isEmpty()) | (<EOL>report_parameter_result.group() != self.ui.report_parameter_value.text()):<EOL><INDENT>self.ui.report_parameter_label.setStyleSheet(error_color)<EOL>self.error_report_parameter = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.report_parameter_label.setStyleSheet(no_error_color)<EOL>self.error_report_parameter = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.report_parameter_label.setStyleSheet(error_color)<EOL>self.error_report_parameter = True<EOL><DEDENT>"""<STR_LIT>"""<EOL>check_num_2 = '<STR_LIT>'<EOL>self.prog_2 = re.compile(check_num_2)<EOL>x_result = self.prog_2.search(self.x_value)<EOL>y_result = self.prog_2.search(self.y_value)<EOL>g_result = self.prog_2.search(self.g_value)<EOL>s_result = self.prog_2.search(self.s_value)<EOL>z_result = self.prog_2.search(self.z_value)<EOL>try:<EOL><INDENT>if x_result.group() != self.ui.x_value.text():<EOL><INDENT>self.ui.particles_label.setStyleSheet(error_color)<EOL>self.ui.x_label.setStyleSheet(error_color)<EOL>self.error_x_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.particles_label.setStyleSheet(no_error_color)<EOL>self.ui.x_label.setStyleSheet(no_error_color)<EOL>self.error_x_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.particles_label.setStyleSheet(no_error_color)<EOL>self.ui.x_label.setStyleSheet(error_color)<EOL>self.error_x_result = True<EOL><DEDENT>try:<EOL><INDENT>if y_result.group() != self.ui.y_value.text():<EOL><INDENT>self.ui.particles_label.setStyleSheet(error_color)<EOL>self.ui.y_label.setStyleSheet(error_color)<EOL>self.error_y_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.particles_label.setStyleSheet(no_error_color)<EOL>self.ui.y_label.setStyleSheet(no_error_color)<EOL>self.error_y_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.particles_label.setStyleSheet(error_color)<EOL>self.ui.y_label.setStyleSheet(error_color)<EOL>self.error_y_result = True<EOL><DEDENT>try:<EOL><INDENT>if g_result.group() != self.ui.g_value.text():<EOL><INDENT>self.ui.organic_label.setStyleSheet(error_color)<EOL>self.ui.g_label.setStyleSheet(error_color)<EOL>self.error_g_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.organic_label.setStyleSheet(no_error_color)<EOL>self.ui.g_label.setStyleSheet(no_error_color)<EOL>self.error_g_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.organic_label.setStyleSheet(error_color)<EOL>self.ui.g_label.setStyleSheet(error_color)<EOL>self.error_g_result = True<EOL><DEDENT>try:<EOL><INDENT>if s_result.group() != self.ui.s_value.text():<EOL><INDENT>self.ui.organic_label.setStyleSheet(error_color)<EOL>self.ui.s_label.setStyleSheet(error_color)<EOL>self.error_s_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.organic_label.setStyleSheet(no_error_color)<EOL>self.ui.s_label.setStyleSheet(no_error_color)<EOL>self.error_x_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.organic_label.setStyleSheet(error_color)<EOL>self.ui.s_label.setStyleSheet(error_color)<EOL>self.error_x_result = True<EOL><DEDENT>try:<EOL><INDENT>if z_result.group() != self.ui.z_value.text():<EOL><INDENT>self.ui.z_label.setStyleSheet(error_color)<EOL>self.error_z_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.z_label.setStyleSheet(no_error_color)<EOL>self.error_z_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.z_label.setStyleSheet(error_color)<EOL>self.error_z_result = True<EOL><DEDENT>check_num_3 = '<STR_LIT>'<EOL>self.prog_3 = re.compile(check_num_3)<EOL>verbose_result = self.prog_3.search(self.verbose_value)<EOL>try:<EOL><INDENT>if verbose_result.group() != self.ui.verbose_value.text():<EOL><INDENT>self.ui.verbose_label.setStyleSheet(error_color)<EOL>self.error_verbose_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.verbose_label.setStyleSheet(no_error_color)<EOL>self.error_verbose_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.verbose_label.setStyleSheet(error_color)<EOL>self.error_verbose_result = True<EOL><DEDENT>"""<STR_LIT>"""<EOL>check_num_4 = '<STR_LIT>'  <EOL>self.prog_4 = re.compile(check_num_4)<EOL>phytoplankton_path_result = self.prog_4.search(self.phytoplankton_path)<EOL>bottom_path_result = self.prog_4.search(self.bottom_path)<EOL>executive_path_result = self.prog_4.search(self.executive_path)<EOL>try:<EOL><INDENT>if phytoplankton_path_result.group() != self.ui.phyto_path.text():<EOL><INDENT>self.ui.phyto_label.setStyleSheet(error_color)<EOL>self.error_phytoplankton_path_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.phyto_label.setStyleSheet(no_error_color)<EOL>self.error_phytoplankton_path_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.phyto_label.setStyleSheet(error_color)<EOL>self.error_phytoplankton_path_result = True<EOL><DEDENT>try:<EOL><INDENT>if bottom_path_result.group() != self.ui.bottom_path.text():<EOL><INDENT>self.ui.bottom_label.setStyleSheet(error_color)<EOL>self.error_bottom_path_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.bottom_label.setStyleSheet(no_error_color)<EOL>self.error_bottom_path_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.bottom_label.setStyleSheet(error_color)<EOL>self.error_bottom_path_result = True<EOL><DEDENT>try:<EOL><INDENT>if executive_path_result.group() != self.ui.exec_path.text():<EOL><INDENT>self.ui.execPath_label.setStyleSheet(error_color)<EOL>self.error_executive_path_result = True<EOL><DEDENT>else:<EOL><INDENT>self.ui.execPath_label.setStyleSheet(no_error_color)<EOL>self.error_executive_path_result = False<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>self.ui.execPath_label.setStyleSheet(error_color)<EOL>self.error_executive_path_result = True<EOL><DEDENT><DEDENT>if (self.error_batch_name == True) | (self.error_report_parameter == True) | (<EOL>self.error_saa_result == True) | (self.error_sza_result == True) | (<EOL>self.error_p_result == True) | (self.error_wavelength_result == True) | (<EOL>self.error_x_result == True) | (self.error_y_result == True) | (<EOL>self.error_g_result == True) | (self.error_s_result == True) | (<EOL>self.error_z_result == True) | (self.error_verbose_result == True) | (<EOL>self.error_phytoplankton_path_result == True) | (self.error_bottom_path_result == True) | (<EOL>self.error_executive_path_result == True):<EOL><INDENT>self.without_error = False<EOL><DEDENT>else:<EOL><INDENT>self.without_error = True<EOL><DEDENT>

This function checks if there is no problem about values given.
If there is a problem with a or some values, their label's color is changed to red,
and call a function to display an error message.
If there is no problem, their label, if it is necessary, is changed to grey (default color).


self.hide_error_message()<EOL>self.ui.show_all_curves.setDisabled(True)<EOL>self.ui.sens.setDisabled(True)<EOL>self.ui.show_grid.setDisabled(True)<EOL>pathname = os.path.dirname(sys.argv[<NUM_LIT:0>])<EOL>path = os.path.abspath(pathname)<EOL>self.verbose_value = self.ui.verbose_value.setText("<STR_LIT>")<EOL>self.report_parameter_value = self.ui.report_parameter_value.setText("<STR_LIT>")<EOL>self.ui.progressBar.reset()<EOL>

This function does all required actions at the beginning when we run the GUI.


if event.button == <NUM_LIT:3>:<EOL><INDENT>if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:<EOL><INDENT>self.pos = QtGui.QCursor().pos()<EOL>self.graphic_context_menu(self.pos)<EOL><DEDENT><DEDENT>

This function intercepts the mouse's right click and its position.


reply = QtGui.QMessageBox.question(self, '<STR_LIT>',<EOL>"<STR_LIT>", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)<EOL>if reply == QtGui.QMessageBox.Yes:<EOL><INDENT>event.accept()<EOL><DEDENT>else:<EOL><INDENT>event.ignore()<EOL><DEDENT>

The following asks to the user if he is sure to quit the GUI.


"""<STR_LIT>"""<EOL>print('<STR_LIT>')<EOL>if self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE:<EOL><INDENT>self.data()<EOL>self.check_values()<EOL>if self.without_error == False:<EOL><INDENT>self.display_error_message()<EOL><DEDENT>elif self.without_error == True:<EOL><INDENT>self.is_running = True<EOL>self.hide_error_message()<EOL>self.write_to_file()<EOL>os.chdir('<STR_LIT>')<EOL>self.progress_bar()<EOL>this_dir = os.path.dirname(os.path.realpath(__file__)).rstrip('<STR_LIT>')<EOL>batch_file = os.path.join(this_dir, "<STR_LIT>" + str(self.batch_name_value) + "<STR_LIT>")<EOL>print(batch_file)<EOL>self.p = subprocess.Popen(<EOL>["<STR_LIT>" + batch_file],<EOL>shell=True)<EOL>if self.ui.progressBar.value() == <NUM_LIT:100>:<EOL><INDENT>self.display_the_graphic(self.num_line, self.wavelength, self.data_wanted, self.information)<EOL><DEDENT><DEDENT><DEDENT>

This function executes planarRad using the batch file.


self.ui.error_label.setScaledContents(False)  <EOL>self.ui.error_text_label.hide()<EOL>

This function hides the error message when all values are correct.


"""<STR_LIT>"""<EOL>default_name = '<STR_LIT>'<EOL>self.ui.graphic_widget.canvas.print_figure(default_name)<EOL>src = '<STR_LIT>' + default_name<EOL>dst = '<STR_LIT>'<EOL>os.system("<STR_LIT>" + "<STR_LIT:U+0020>" + src + "<STR_LIT:U+0020>" + dst)<EOL>

This function programs the button to save the figure displayed
and save it in a png file in the current repository.


"""<STR_LIT>"""<EOL>if (self.is_running == True) & (self.ui.tabWidget.currentIndex() == TabWidget.NORMAL_MODE):<EOL><INDENT>cancel = QtGui.QMessageBox.question(self.ui.cancel, '<STR_LIT>', "<STR_LIT>",<EOL>QtGui.QMessageBox.Yes,<EOL>QtGui.QMessageBox.No)<EOL>if cancel == QtGui.QMessageBox.Yes:<EOL><INDENT>self.is_running = False<EOL>os.kill(self.p.pid, signal.SIGTERM)<EOL>print("<STR_LIT>")<EOL>self.ui.progressBar.reset()<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>


if self.authorized_display == True:<EOL><INDENT>try:<EOL><INDENT>self.display_the_graphic(self.num_line, self.wavelength, self.data_wanted, self.information)<EOL>self.ui.mouse_coordinate.setText("<STR_LIT>" % (x, y))<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

The following update labels about mouse coordinates.


menu_title = menu_data['<STR_LIT:title>']<EOL>menu = CursesMenu(menu_title)<EOL>for item in menu_data["<STR_LIT>"]:<EOL><INDENT>item_type = item["<STR_LIT:type>"]<EOL>item_title = item["<STR_LIT:title>"]<EOL>if item_type == menuItem.COMMAND:<EOL><INDENT>item_command = item["<STR_LIT>"]<EOL>menu.append_item(CommandItem(item_title, item_command, menu))<EOL><DEDENT>elif item_type == menuItem.FUNCTION:<EOL><INDENT>item_function = item["<STR_LIT>"]<EOL>menu.append_item(FunctionItem(item_title, item_function, menu))<EOL><DEDENT>elif item_type == menuItem.EXITMENU:<EOL><INDENT>menu.append_item(ExitItem(item_title, menu))<EOL><DEDENT>elif item_type == menuItem.NUMBER:<EOL><INDENT>menu.append_item(SelectionItem(item_title, menu))<EOL><DEDENT>elif item_type == menuItem.MENU:<EOL><INDENT>new_menu = parse_old_menu(item)<EOL>menu.append_item(SubmenuItem(item_title, menu, new_menu))<EOL><DEDENT><DEDENT>return menu<EOL>

Take an old-style menuData dictionary and return a CursesMenu

:param dict menu_data:
:return: A new CursesMenu
:rtype: CursesMenu


did_remove = self.remove_exit()<EOL>item.menu = self<EOL>self.items.append(item)<EOL>if did_remove:<EOL><INDENT>self.add_exit()<EOL><DEDENT>if self.screen:<EOL><INDENT>max_row, max_cols = self.screen.getmaxyx()<EOL>if max_row < <NUM_LIT:6> + len(self.items):<EOL><INDENT>self.screen.resize(<NUM_LIT:6> + len(self.items), max_cols)<EOL><DEDENT>self.draw()<EOL><DEDENT>

Add an item to the end of the menu before the exit item

:param MenuItem item: The item to be added


self.current_option = option<EOL>self.draw()<EOL>

Go to the option entered by the user as a number

:param option: the option to go to
:type option: int


user_input = self.get_input()<EOL>go_to_max = ord("<STR_LIT>") if len(self.items) >= <NUM_LIT:9> else ord(str(len(self.items)))<EOL>if ord('<STR_LIT:1>') <= user_input <= go_to_max:<EOL><INDENT>self.go_to(user_input - ord('<STR_LIT:0>') - <NUM_LIT:1>)<EOL><DEDENT>elif user_input == curses.KEY_DOWN:<EOL><INDENT>self.go_down()<EOL><DEDENT>elif user_input == curses.KEY_UP:<EOL><INDENT>self.go_up()<EOL><DEDENT>elif user_input == ord("<STR_LIT:\n>"):<EOL><INDENT>self.select()<EOL><DEDENT>return user_input<EOL>

Gets the next single character and decides what to do with it


pass<EOL>

Override to add any setup actions necessary for the item


def __init__(self, text, menu=None, should_exit=False):

self.text = text<EOL>self.menu = menu<EOL>self.should_exit = should_exit<EOL>

:ivar str text: The text shown for this menu item
:ivar CursesMenu menu: The menu to which this item belongs
:ivar bool should_exit: Whether the menu should exit once this item's action is done


return "<STR_LIT>" % (index + <NUM_LIT:1>, self.text)<EOL>

How this item should be displayed in the menu. Can be overridden, but should keep the same signature.

Default is:

    1 - Item 1

    2 - Another Item

:param int index: The index of the item in the items list of the menu
:return: The representation of the item to be shown in a menu
:rtype: str


return self._running.is_set()<EOL>

:return: True if the menu is started and hasn't been paused


self.previous_active_menu = CursesMenu.currently_active_menu<EOL>CursesMenu.currently_active_menu = None<EOL>self.should_exit = False<EOL>if show_exit_option is None:<EOL><INDENT>show_exit_option = self.show_exit_option<EOL><DEDENT>if show_exit_option:<EOL><INDENT>self.add_exit()<EOL><DEDENT>else:<EOL><INDENT>self.remove_exit()<EOL><DEDENT>try:<EOL><INDENT>self._main_thread = threading.Thread(target=self._wrap_start, daemon=True)<EOL><DEDENT>except TypeError:<EOL><INDENT>self._main_thread = threading.Thread(target=self._wrap_start)<EOL>self._main_thread.daemon = True<EOL><DEDENT>self._main_thread.start()<EOL>

Start the menu in a new thread and allow the user to interact with it.
The thread is a daemon, so :meth:`join()<cursesmenu.CursesMenu.join>` should be called if there's a possibility\
that the main thread will exit before the menu is done

:param bool show_exit_option: Whether the exit item should be shown, defaults to\
the value set in the constructor


self.return_value = self.function(*self.args, **self.kwargs)<EOL>


def __init__(self, text, command, arguments=None, menu=None, should_exit=False):

super(CommandItem, self).__init__(text=text, menu=menu, should_exit=should_exit)<EOL>self.command = command<EOL>if arguments:<EOL><INDENT>self.arguments = arguments<EOL><DEDENT>else:<EOL><INDENT>self.arguments = []<EOL><DEDENT>self.exit_status = None<EOL>

:ivar str command: The console command to be executed
:ivar list[str] arguments: An optional list of string arguments to be passed to the command
:ivar int exit_status: the exit status of the command, None if it hasn't been run yet


def __init__(self, text, submenu, menu=None, should_exit=False):

super(SubmenuItem, self).__init__(text=text, menu=menu, should_exit=should_exit)<EOL>self.submenu = submenu<EOL>if menu:<EOL><INDENT>self.submenu.parent = menu<EOL><DEDENT>

:ivar CursesMenu self.submenu: The submenu to be opened when this item is selected


def _prepare_args(log_likelihood_fn, state,<EOL>log_likelihood=None, description='<STR_LIT>'):

state_parts = list(state) if mcmc_util.is_list_like(state) else [state]<EOL>state_parts = [tf.convert_to_tensor(s, name='<STR_LIT>')<EOL>for s in state_parts]<EOL>log_likelihood = _maybe_call_fn(<EOL>log_likelihood_fn,<EOL>state_parts,<EOL>log_likelihood,<EOL>description)<EOL>return [state_parts, log_likelihood]<EOL>

Processes input args to meet list-like assumptions.


def one_step(self, current_state, previous_kernel_results):

with tf.compat.v1.name_scope(<EOL>name=mcmc_util.make_name(self.name, '<STR_LIT>', '<STR_LIT>'),<EOL>values=[self._seed_stream,<EOL>current_state,<EOL>previous_kernel_results.log_likelihood]):<EOL><INDENT>with tf.compat.v1.name_scope('<STR_LIT>'):<EOL><INDENT>[<EOL>init_state_parts,<EOL>init_log_likelihood<EOL>] = _prepare_args(<EOL>self.log_likelihood_fn,<EOL>current_state,<EOL>previous_kernel_results.log_likelihood)<EOL><DEDENT>normal_samples = self.normal_sampler_fn(self._seed_stream())  <EOL>normal_samples = list(normal_samples) if mcmc_util.is_list_like(<EOL>normal_samples) else [normal_samples]<EOL>u = tf.random.uniform(<EOL>shape=tf.shape(init_log_likelihood),<EOL>seed=self._seed_stream(),<EOL>dtype=init_log_likelihood.dtype.base_dtype,<EOL>)<EOL>threshold = init_log_likelihood + tf.math.log(u)<EOL>starting_angle = tf.random.uniform(<EOL>shape=tf.shape(init_log_likelihood),<EOL>minval=<NUM_LIT:0.>,<EOL>maxval=<NUM_LIT:2> * np.pi,<EOL>name='<STR_LIT>',<EOL>seed=self._seed_stream(),<EOL>dtype=init_log_likelihood.dtype.base_dtype,<EOL>)<EOL>starting_angle_min = starting_angle - <NUM_LIT:2> * np.pi<EOL>starting_angle_max = starting_angle<EOL>starting_state_parts = _rotate_on_ellipse(<EOL>init_state_parts, normal_samples, starting_angle)<EOL>starting_log_likelihood = self.log_likelihood_fn(*starting_state_parts)  <EOL>def chain_not_done(<EOL>angle,<EOL>angle_min,<EOL>angle_max,<EOL>current_state_parts,<EOL>current_log_likelihood):<EOL><INDENT>del angle, angle_min, angle_max, current_state_parts<EOL>return tf.reduce_any(current_log_likelihood < threshold)<EOL><DEDENT>def sample_next_angle(<EOL>angle,<EOL>angle_min,<EOL>angle_max,<EOL>current_state_parts,<EOL>current_log_likelihood):<EOL><INDENT>"""<STR_LIT>"""<EOL>chain_not_done = current_log_likelihood < threshold<EOL>angle_min = tf.where(<EOL>tf.math.logical_and(angle < <NUM_LIT:0>, chain_not_done),<EOL>angle,<EOL>angle_min)<EOL>angle_max = tf.where(<EOL>tf.math.logical_and(angle >= <NUM_LIT:0>, chain_not_done),<EOL>angle,<EOL>angle_max)<EOL>new_angle = tf.random.uniform(<EOL>shape=tf.shape(current_log_likelihood),<EOL>minval=angle_min,<EOL>maxval=angle_max,<EOL>seed=self._seed_stream(),<EOL>dtype=angle.dtype.base_dtype<EOL>)<EOL>angle = tf.where(chain_not_done, new_angle, angle)<EOL>next_state_parts = _rotate_on_ellipse(<EOL>init_state_parts, normal_samples, angle)<EOL>new_state_parts = []<EOL>broadcasted_chain_not_done = _right_pad_with_ones(<EOL>chain_not_done, tf.rank(next_state_parts[<NUM_LIT:0>]))<EOL>for n_state, c_state in zip(next_state_parts, current_state_parts):<EOL><INDENT>new_state_part = tf.where(<EOL>tf.broadcast_to(<EOL>broadcasted_chain_not_done,<EOL>tf.shape(n_state)),<EOL>n_state,<EOL>c_state)<EOL>new_state_parts.append(new_state_part)<EOL><DEDENT>return (<EOL>angle,<EOL>angle_min,<EOL>angle_max,<EOL>new_state_parts,<EOL>self.log_likelihood_fn(*new_state_parts)  <EOL>)<EOL><DEDENT>[<EOL>next_angle,<EOL>_,<EOL>_,<EOL>next_state_parts,<EOL>next_log_likelihood,<EOL>] = tf.while_loop(<EOL>cond=chain_not_done,<EOL>body=sample_next_angle,<EOL>loop_vars=[<EOL>starting_angle,<EOL>starting_angle_min,<EOL>starting_angle_max,<EOL>starting_state_parts,<EOL>starting_log_likelihood<EOL>])<EOL>return [<EOL>next_state_parts if mcmc_util.is_list_like(<EOL>current_state) else next_state_parts[<NUM_LIT:0>],<EOL>EllipticalSliceSamplerKernelResults(<EOL>log_likelihood=next_log_likelihood,<EOL>angle=next_angle,<EOL>normal_samples=normal_samples,<EOL>),<EOL>]<EOL><DEDENT>

Runs one iteration of the Elliptical Slice Sampler.

        Args:
          current_state: `Tensor` or Python `list` of `Tensor`s representing the
            current state(s) of the Markov chain(s). The first `r` dimensions
            index independent chains,
            `r = tf.rank(log_likelihood_fn(*normal_sampler_fn()))`.
          previous_kernel_results: `collections.namedtuple` containing `Tensor`s
            representing values from previous calls to this function (or from the
            `bootstrap_results` function.)

        Returns:
          next_state: Tensor or Python list of `Tensor`s representing the state(s)
            of the Markov chain(s) after taking exactly one step. Has same type and
            shape as `current_state`.
          kernel_results: `collections.namedtuple` of internal calculations used to
            advance the chain.

        Raises:
          TypeError: if `not log_likelihood.dtype.is_floating`.


if not tf.executing_eagerly():<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>with tf.compat.v1.name_scope(<EOL>name,<EOL>default_name="<STR_LIT>",<EOL>values=[<EOL>current_state, step_size, seed, current_target_log_prob,<EOL>current_grads_target_log_prob<EOL>]):<EOL><INDENT>with tf.compat.v1.name_scope("<STR_LIT>"):<EOL><INDENT>current_state = [tf.convert_to_tensor(value=s) for s in current_state]<EOL>step_size = [tf.convert_to_tensor(value=s) for s in step_size]<EOL>value_and_gradients_fn = lambda *args: tfp.math.value_and_gradient(  <EOL>target_log_prob_fn, args)<EOL>value_and_gradients_fn = _embed_no_none_gradient_check(<EOL>value_and_gradients_fn)<EOL>if (current_target_log_prob is None or<EOL>current_grads_target_log_prob is None):<EOL><INDENT>(current_target_log_prob,<EOL>current_grads_target_log_prob) = value_and_gradients_fn(*current_state)<EOL><DEDENT>seed_stream = tfd.SeedStream(seed, "<STR_LIT>")<EOL>current_momentum = []<EOL>for state_tensor in current_state:<EOL><INDENT>momentum_tensor = tf.random.normal(<EOL>shape=tf.shape(input=state_tensor),<EOL>dtype=state_tensor.dtype,<EOL>seed=seed_stream())<EOL>current_momentum.append(momentum_tensor)<EOL><DEDENT>log_slice_sample = tf.math.log(tf.random.uniform([], seed=seed_stream()))<EOL>log_slice_sample += _log_joint(current_target_log_prob,<EOL>current_momentum)<EOL>reverse_state = current_state<EOL>reverse_target_log_prob = current_target_log_prob<EOL>reverse_grads_target_log_prob = current_grads_target_log_prob<EOL>reverse_momentum = current_momentum<EOL>forward_state = current_state<EOL>forward_target_log_prob = current_target_log_prob<EOL>forward_grads_target_log_prob = current_grads_target_log_prob<EOL>forward_momentum = current_momentum<EOL>next_state = current_state<EOL>next_target_log_prob = current_target_log_prob<EOL>next_grads_target_log_prob = current_grads_target_log_prob<EOL>depth = <NUM_LIT:0><EOL>num_states = <NUM_LIT:1><EOL>continue_trajectory = True<EOL><DEDENT>while continue_trajectory:<EOL><INDENT>direction = tfp.math.random_rademacher([], seed=seed_stream())<EOL>if direction < <NUM_LIT:0>:<EOL><INDENT>[<EOL>reverse_state,<EOL>reverse_target_log_prob,<EOL>reverse_grads_target_log_prob,<EOL>reverse_momentum,<EOL>_,<EOL>_,<EOL>_,<EOL>_,<EOL>next_state_in_subtree,<EOL>next_target_log_prob_in_subtree,<EOL>next_grads_target_log_prob_in_subtree,<EOL>num_states_in_subtree,<EOL>continue_trajectory,<EOL>] = _build_tree(<EOL>value_and_gradients_fn=value_and_gradients_fn,<EOL>current_state=reverse_state,<EOL>current_target_log_prob=reverse_target_log_prob,<EOL>current_grads_target_log_prob=reverse_grads_target_log_prob,<EOL>current_momentum=reverse_momentum,<EOL>direction=direction,<EOL>depth=depth,<EOL>step_size=step_size,<EOL>log_slice_sample=log_slice_sample,<EOL>seed=seed_stream())<EOL><DEDENT>else:<EOL><INDENT>[<EOL>_,<EOL>_,<EOL>_,<EOL>_,<EOL>forward_state,<EOL>forward_target_log_prob,<EOL>forward_grads_target_log_prob,<EOL>forward_momentum,<EOL>next_state_in_subtree,<EOL>next_target_log_prob_in_subtree,<EOL>next_grads_target_log_prob_in_subtree,<EOL>num_states_in_subtree,<EOL>continue_trajectory,<EOL>] = _build_tree(<EOL>value_and_gradients_fn=value_and_gradients_fn,<EOL>current_state=forward_state,<EOL>current_target_log_prob=forward_target_log_prob,<EOL>current_grads_target_log_prob=forward_grads_target_log_prob,<EOL>current_momentum=forward_momentum,<EOL>direction=direction,<EOL>depth=depth,<EOL>step_size=step_size,<EOL>log_slice_sample=log_slice_sample,<EOL>seed=seed_stream())<EOL><DEDENT>if continue_trajectory:<EOL><INDENT>accept_state_in_subtree = _random_bernoulli(<EOL>[],<EOL>probs=tf.minimum(<NUM_LIT:1.>, num_states_in_subtree / num_states),<EOL>dtype=tf.bool,<EOL>seed=seed_stream())<EOL>if accept_state_in_subtree:<EOL><INDENT>next_state = next_state_in_subtree<EOL>next_target_log_prob = next_target_log_prob_in_subtree<EOL>next_grads_target_log_prob = next_grads_target_log_prob_in_subtree<EOL><DEDENT><DEDENT>has_no_u_turn = tf.logical_and(<EOL>_has_no_u_turn(forward_state, reverse_state, forward_momentum),<EOL>_has_no_u_turn(forward_state, reverse_state, reverse_momentum))<EOL>continue_trajectory = continue_trajectory and has_no_u_turn<EOL>num_states += num_states_in_subtree<EOL>depth += <NUM_LIT:1><EOL><DEDENT>return next_state, next_target_log_prob, next_grads_target_log_prob<EOL><DEDENT>

Simulates a No-U-Turn Sampler (NUTS) trajectory.

    Args:
      target_log_prob_fn: Python callable which takes an argument like
        `*current_state` and returns its (possibly unnormalized) log-density under
        the target distribution.
      current_state: List of `Tensor`s representing the states to simulate from.
      step_size: List of `Tensor`s representing the step sizes for the leapfrog
        integrator. Must have same shape as `current_state`.
      seed: Integer to seed the random number generator.
      current_target_log_prob: Scalar `Tensor` representing the value of
        `target_log_prob_fn` at the `current_state`.
      current_grads_target_log_prob: List of `Tensor`s representing gradient of
        `current_target_log_prob` with respect to `current_state`. Must have same
        shape as `current_state`.
      name: A name for the operation.

    Returns:
      next_state: List of `Tensor`s representing the next states of the NUTS
        trajectory. Has same shape as `current_state`.
      next_target_log_prob: Scalar `Tensor` representing the value of
        `target_log_prob_fn` at `next_state`.
      next_grads_target_log_prob: List of `Tensor`s representing the gradient of
        `next_target_log_prob` with respect to `next_state`.

    Raises:
      NotImplementedError: If the execution mode is not eager.


def metropolis_hastings_step(current_state: State,<EOL>proposed_state: State,<EOL>energy_change: FloatTensor,<EOL>seed=None) -> Tuple[State, tf.Tensor, tf.Tensor]:

flat_current = tf.nest.flatten(current_state)<EOL>flat_proposed = nest.flatten_up_to(current_state, proposed_state)<EOL>flat_current = [<EOL>p if c is None else c for p, c in zip(flat_proposed, flat_current)<EOL>]<EOL>current_state = tf.nest.pack_sequence_as(current_state, flat_current)<EOL>current_state = tf.nest.map_structure(tf.convert_to_tensor, current_state)<EOL>proposed_state = tf.nest.map_structure(tf.convert_to_tensor, proposed_state)<EOL>energy_change = tf.convert_to_tensor(value=energy_change)<EOL>log_accept_ratio = -energy_change<EOL>log_uniform = tf.math.log(<EOL>tf.random.uniform(<EOL>shape=tf.shape(input=log_accept_ratio),<EOL>dtype=log_accept_ratio.dtype.base_dtype,<EOL>seed=seed))<EOL>is_accepted = log_uniform < log_accept_ratio<EOL>next_state = mcmc_util.choose(<EOL>is_accepted, proposed_state, current_state, name='<STR_LIT>')<EOL>return next_state, is_accepted, log_uniform<EOL>

Metropolis-Hastings step.

    This probabilistically chooses between `current_state` and `proposed_state`
    based on the `energy_change` so as to preserve detailed balance.

    Energy change is the negative of `log_accept_ratio`.

    Args:
      current_state: Current state.
      proposed_state: Proposed state.
      energy_change: E(proposed_state) - E(previous_state).
      seed: For reproducibility.

    Returns:
      new_state: The chosen state.
      is_accepted: Whether the proposed state was accepted.
      log_uniform: The random number that was used to select between the two
        states.


def leapfrog_step(leapfrog_step_state: LeapFrogStepState,<EOL>step_size: FloatTensor, target_log_prob_fn: PotentialFn,<EOL>kinetic_energy_fn: PotentialFn<EOL>) -> Tuple[LeapFrogStepState, LeapFrogStepExtras]:

state = leapfrog_step_state.state<EOL>state_grads = leapfrog_step_state.state_grads<EOL>momentum = leapfrog_step_state.momentum<EOL>step_size = maybe_broadcast_structure(step_size, state)<EOL>state = tf.nest.map_structure(tf.convert_to_tensor, state)<EOL>momentum = tf.nest.map_structure(tf.convert_to_tensor, momentum)<EOL>state = tf.nest.map_structure(tf.convert_to_tensor, state)<EOL>if state_grads is None:<EOL><INDENT>_, _, state_grads = call_and_grads(target_log_prob_fn, state)<EOL><DEDENT>else:<EOL><INDENT>state_grads = tf.nest.map_structure(tf.convert_to_tensor, state_grads)<EOL><DEDENT>momentum = tf.nest.map_structure(lambda m, sg, s: m + <NUM_LIT:0.5> * sg * s, momentum,<EOL>state_grads, step_size)<EOL>kinetic_energy, kinetic_energy_extra, momentum_grads = call_and_grads(<EOL>kinetic_energy_fn, momentum)<EOL>state = tf.nest.map_structure(lambda x, mg, s: x + mg * s, state,<EOL>momentum_grads, step_size)<EOL>target_log_prob, state_extra, state_grads = call_and_grads(<EOL>target_log_prob_fn, state)<EOL>momentum = tf.nest.map_structure(lambda m, sg, s: m + <NUM_LIT:0.5> * sg * s, momentum,<EOL>state_grads, step_size)<EOL>return LeapFrogStepState(state, state_grads, momentum), LeapFrogStepExtras(<EOL>target_log_prob, state_extra, kinetic_energy, kinetic_energy_extra)<EOL>

Leapfrog `TransitionOperator`.

    Args:
      leapfrog_step_state: LeapFrogStepState.
      step_size: Step size, structure broadcastable to the `target_log_prob_fn`
        state.
      target_log_prob_fn: Target log prob fn.
      kinetic_energy_fn: Kinetic energy fn.

    Returns:
      leapfrog_step_state: LeapFrogStepState.
      leapfrog_step_extras: LeapFrogStepExtras.


def maybe_broadcast_structure(from_structure: Any, to_structure: Any) -> Any:

flat_from = tf.nest.flatten(from_structure)<EOL>flat_to = tf.nest.flatten(to_structure)<EOL>if len(flat_from) == <NUM_LIT:1>:<EOL><INDENT>flat_from *= len(flat_to)<EOL><DEDENT>return tf.nest.pack_sequence_as(to_structure, flat_from)<EOL>

Maybe broadcasts `from_structure` to `to_structure`.

    If `from_structure` is a singleton, it is tiled to match the structure of
    `to_structure`. Note that the elements in `from_structure` are not copied if
    this tiling occurs.

    Args:
      from_structure: A structure.
      to_structure: A structure.

    Returns:
      new_from_structure: Same structure as `to_structure`.


return self._shift<EOL>

The `shift` `Tensor` in `Y = scale @ X + shift`.


def __init__(self, validate_args=False, name="<STR_LIT>"):

self._name = name<EOL>super(Square, self).__init__(<EOL>forward_min_event_ndims=<NUM_LIT:0>,<EOL>validate_args=validate_args,<EOL>name=name)<EOL>

Instantiates the `Square` bijector.

        Args:
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          name: Python `str` name given to ops managed by this object.


def _replace_event_shape_in_shape_tensor(<EOL>input_shape, event_shape_in, event_shape_out, validate_args):

output_tensorshape, is_validated = _replace_event_shape_in_tensorshape(<EOL>tensorshape_util.constant_value_as_shape(input_shape),<EOL>event_shape_in,<EOL>event_shape_out)<EOL>validation_dependencies = (<EOL>map(tf.identity, (event_shape_in, event_shape_out))<EOL>if validate_args else ())<EOL>if (tensorshape_util.is_fully_defined(output_tensorshape) and<EOL>(is_validated or not validate_args)):<EOL><INDENT>with tf.control_dependencies(validation_dependencies):<EOL><INDENT>output_shape = tf.convert_to_tensor(<EOL>value=output_tensorshape, name='<STR_LIT>', dtype_hint=tf.int32)<EOL><DEDENT>return output_shape, output_tensorshape<EOL><DEDENT>with tf.control_dependencies(validation_dependencies):<EOL><INDENT>event_shape_in_ndims = (<EOL>tf.size(input=event_shape_in)<EOL>if tensorshape_util.num_elements(event_shape_in.shape) is None else<EOL>tensorshape_util.num_elements(event_shape_in.shape))<EOL>input_non_event_shape, input_event_shape = tf.split(<EOL>input_shape, num_or_size_splits=[-<NUM_LIT:1>, event_shape_in_ndims])<EOL><DEDENT>additional_assertions = []<EOL>if is_validated:<EOL><INDENT>pass<EOL><DEDENT>elif validate_args:<EOL><INDENT>mask = event_shape_in >= <NUM_LIT:0><EOL>explicit_input_event_shape = tf.boolean_mask(<EOL>tensor=input_event_shape, mask=mask)<EOL>explicit_event_shape_in = tf.boolean_mask(<EOL>tensor=event_shape_in, mask=mask)<EOL>additional_assertions.append(<EOL>assert_util.assert_equal(<EOL>explicit_input_event_shape,<EOL>explicit_event_shape_in,<EOL>message='<STR_LIT>'))<EOL><DEDENT>with tf.control_dependencies(additional_assertions):<EOL><INDENT>output_shape = tf.concat([input_non_event_shape, event_shape_out], axis=<NUM_LIT:0>,<EOL>name='<STR_LIT>')<EOL><DEDENT>return output_shape, output_tensorshape<EOL>

Replaces the rightmost dims in a `Tensor` representing a shape.

    Args:
      input_shape: a rank-1 `Tensor` of integers
      event_shape_in: the event shape expected to be present in rightmost dims
        of `shape_in`.
      event_shape_out: the event shape with which to replace `event_shape_in` in
        the rightmost dims of `input_shape`.
      validate_args: Python `bool` indicating whether arguments should
        be checked for correctness.

    Returns:
      output_shape: A rank-1 integer `Tensor` with the same contents as
        `input_shape` except for the event dims, which are replaced with
        `event_shape_out`.


def __init__(self, event_shape_out, event_shape_in=(-<NUM_LIT:1>,),<EOL>validate_args=False, name=None):

with tf.name_scope(name or '<STR_LIT>'):<EOL><INDENT>event_shape_out = tf.convert_to_tensor(<EOL>value=event_shape_out, name='<STR_LIT>', dtype_hint=tf.int32)<EOL>event_shape_in = tf.convert_to_tensor(<EOL>value=event_shape_in, name='<STR_LIT>', dtype_hint=tf.int32)<EOL>forward_min_event_ndims_ = tensorshape_util.num_elements(<EOL>event_shape_in.shape)<EOL>if forward_min_event_ndims_ is None:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>inverse_min_event_ndims_ = tensorshape_util.num_elements(<EOL>event_shape_out.shape)<EOL>if inverse_min_event_ndims_ is None:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>assertions = []<EOL>assertions.extend(_maybe_check_valid_shape(<EOL>event_shape_out, validate_args))<EOL>assertions.extend(_maybe_check_valid_shape(<EOL>event_shape_in, validate_args))<EOL>if assertions:<EOL><INDENT>with tf.control_dependencies(assertions):<EOL><INDENT>event_shape_in = tf.identity(<EOL>event_shape_in, name='<STR_LIT>')<EOL>event_shape_out = tf.identity(<EOL>event_shape_out, name='<STR_LIT>')<EOL><DEDENT><DEDENT>self._event_shape_in = event_shape_in<EOL>self._event_shape_out = event_shape_out<EOL>super(Reshape, self).__init__(<EOL>forward_min_event_ndims=forward_min_event_ndims_,<EOL>inverse_min_event_ndims=inverse_min_event_ndims_,<EOL>is_constant_jacobian=True,<EOL>validate_args=validate_args,<EOL>name=name or '<STR_LIT>')<EOL><DEDENT>

Creates a `Reshape` bijector.

        Args:
          event_shape_out: An `int`-like vector-shaped `Tensor`
            representing the event shape of the transformed output.
          event_shape_in: An optional `int`-like vector-shape `Tensor`
            representing the event shape of the input. This is required in
            order to define inverse operations; the default of (-1,)
            assumes a vector-shaped input.
          validate_args: Python `bool` indicating whether arguments should
            be checked for correctness.
          name: Python `str`, name given to ops managed by this object.

        Raises:
          TypeError: if either `event_shape_in` or `event_shape_out` has
            non-integer `dtype`.
          ValueError: if either of `event_shape_in` or `event_shape_out`
           has non-vector shape (`rank > 1`), or if their sizes do not
           match.


def _validate_block_sizes(block_sizes, bijectors, validate_args):

block_sizes_shape = block_sizes.shape<EOL>if tensorshape_util.is_fully_defined(block_sizes_shape):<EOL><INDENT>if (tensorshape_util.rank(block_sizes_shape) != <NUM_LIT:1> or<EOL>(tensorshape_util.num_elements(block_sizes_shape) != len(bijectors))):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(block_sizes_shape, len(bijectors)))<EOL><DEDENT>return block_sizes<EOL><DEDENT>elif validate_args:<EOL><INDENT>message = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>with tf.control_dependencies([<EOL>assert_util.assert_equal(<EOL>tf.size(input=block_sizes), len(bijectors), message=message),<EOL>assert_util.assert_equal(tf.rank(block_sizes), <NUM_LIT:1>)<EOL>]):<EOL><INDENT>return tf.identity(block_sizes)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return block_sizes<EOL><DEDENT>


def vector_size_to_square_matrix_size(d, validate_args, name=None):

if isinstance(d, (float, int, np.generic, np.ndarray)):<EOL><INDENT>n = (-<NUM_LIT:1> + np.sqrt(<NUM_LIT:1> + <NUM_LIT:8> * d)) / <NUM_LIT><EOL>if float(int(n)) != n:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return int(n)<EOL><DEDENT>else:<EOL><INDENT>with tf.name_scope(name or "<STR_LIT>") as name:<EOL><INDENT>n = (-<NUM_LIT:1.> + tf.sqrt(<NUM_LIT:1> + <NUM_LIT> * tf.cast(d, dtype=tf.float32))) / <NUM_LIT><EOL>if validate_args:<EOL><INDENT>with tf.control_dependencies([<EOL>assert_util.assert_equal(<EOL>tf.cast(tf.cast(n, dtype=tf.int32), dtype=tf.float32),<EOL>n,<EOL>message="<STR_LIT>")<EOL>]):<EOL><INDENT>n = tf.identity(n)<EOL><DEDENT><DEDENT>return tf.cast(n, d.dtype)<EOL><DEDENT><DEDENT>


if isinstance(bijector, tfb.CholeskyToInvCholesky):<EOL><INDENT>def additional_check(dist):<EOL><INDENT>return (tensorshape_util.rank(dist.event_shape) == <NUM_LIT:2> and<EOL>int(dist.event_shape[<NUM_LIT:0>]) == int(dist.event_shape[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>additional_check = lambda dist: True<EOL><DEDENT>def distribution_filter(dist):<EOL><INDENT>if not dtype_util.is_floating(dist.dtype):<EOL><INDENT>return False<EOL><DEDENT>if bijector.forward_min_event_ndims > tensorshape_util.rank(<EOL>dist.event_shape):<EOL><INDENT>return False<EOL><DEDENT>return additional_check(dist)<EOL><DEDENT>return distribution_filter<EOL>

Returns filter function f s.t. f(dist)=True => bijector can act on dist.


def _maybe_assert_valid_concentration(self, concentration, validate_args):

if not validate_args:<EOL><INDENT>return concentration<EOL><DEDENT>return distribution_util.with_dependencies([<EOL>assert_util.assert_positive(<EOL>concentration, message="<STR_LIT>"),<EOL>], concentration)<EOL>

Checks the validity of a concentration parameter.


super(Inline, self).__init__(<EOL>forward_min_event_ndims=forward_min_event_ndims,<EOL>inverse_min_event_ndims=inverse_min_event_ndims,<EOL>is_constant_jacobian=is_constant_jacobian,<EOL>validate_args=validate_args,<EOL>name=name)<EOL>self._forward_fn = forward_fn<EOL>self._inverse_fn = inverse_fn<EOL>self._inverse_log_det_jacobian_fn = inverse_log_det_jacobian_fn<EOL>self._forward_log_det_jacobian_fn = forward_log_det_jacobian_fn<EOL>self._forward_event_shape_fn = forward_event_shape_fn<EOL>self._forward_event_shape_tensor_fn = forward_event_shape_tensor_fn<EOL>self._inverse_event_shape_fn = inverse_event_shape_fn<EOL>self._inverse_event_shape_tensor_fn = inverse_event_shape_tensor_fn<EOL>

Creates a `Bijector` from callables.

        Args:
          forward_fn: Python callable implementing the forward transformation.
          inverse_fn: Python callable implementing the inverse transformation.
          inverse_log_det_jacobian_fn: Python callable implementing the
            log o det o jacobian of the inverse transformation.
          forward_log_det_jacobian_fn: Python callable implementing the
            log o det o jacobian of the forward transformation.
          forward_event_shape_fn: Python callable implementing non-identical
            static event shape changes. Default: shape is assumed unchanged.
          forward_event_shape_tensor_fn: Python callable implementing non-identical
            event shape changes. Default: shape is assumed unchanged.
          inverse_event_shape_fn: Python callable implementing non-identical
            static event shape changes. Default: shape is assumed unchanged.
          inverse_event_shape_tensor_fn: Python callable implementing non-identical
            event shape changes. Default: shape is assumed unchanged.
          is_constant_jacobian: Python `bool` indicating that the Jacobian is
            constant for all input arguments.
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          forward_min_event_ndims: Python `int` indicating the minimal
            dimensionality this bijector acts on.
          inverse_min_event_ndims: Python `int` indicating the minimal
            dimensionality this bijector acts on.
          name: Python `str`, name given to ops managed by this object.


def _lookup(self, x=None, y=None, kwargs=None):

mapping = _Mapping(x=x, y=y, kwargs=kwargs)<EOL>subkey = mapping.subkey<EOL>if x is not None:<EOL><INDENT>mapping = self._from_x[x].get(subkey, mapping).merge(x=x)<EOL><DEDENT>if y is not None:<EOL><INDENT>mapping = self._from_y[y].get(subkey, mapping).merge(y=y)<EOL><DEDENT>return mapping<EOL>

Helper which retrieves mapping info from forward/inverse dicts.


return self._deep_tuple(self.kwargs)<EOL>

Returns subkey used for caching (nested under either `x` or `y`).


def merge(self, x=None, y=None, ildj=None, kwargs=None, mapping=None):

if mapping is None:<EOL><INDENT>mapping = _Mapping(x=x, y=y, ildj=ildj, kwargs=kwargs)<EOL><DEDENT>elif any(arg is not None for arg in [x, y, ildj, kwargs]):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return _Mapping(<EOL>x=self._merge(self.x, mapping.x),<EOL>y=self._merge(self.y, mapping.y),<EOL>ildj=self._merge(self.ildj, mapping.ildj),<EOL>kwargs=self._merge(self.kwargs, mapping.kwargs, use_equals=True))<EOL>

Returns new _Mapping with args merged with self.

        Args:
          x: `Tensor` or None. Input to forward; output of inverse.
          y: `Tensor` or None. Input to inverse; output of forward.
          ildj: `Tensor`. This is the (un-reduce_sum'ed) inverse log det jacobian.
          kwargs: Python dictionary. Extra args supplied to forward/inverse/etc
            functions.
          mapping: Instance of _Mapping to merge. Can only be specified if no other
            arg is specified.

        Returns:
          mapping: New instance of `_Mapping` which has inputs merged with self.

        Raises:
          ValueError: if mapping and any other arg is not `None`.


def forward(self, x, name="<STR_LIT>", **kwargs):

return self._call_forward(x, name, **kwargs)<EOL>

Returns the forward `Bijector` evaluation, i.e., X = g(Y).

        Args:
          x: `Tensor`. The input to the "forward" evaluation.
          name: The name to give this op.
          **kwargs: Named arguments forwarded to subclass implementation.

        Returns:
          `Tensor`.

        Raises:
          TypeError: if `self.dtype` is specified and `x.dtype` is not
            `self.dtype`.
          NotImplementedError: if `_forward` is not implemented.


with self._name_scope(name):<EOL><INDENT>input_shape = tf.convert_to_tensor(<EOL>value=input_shape, dtype=tf.int32, name="<STR_LIT>")<EOL>return self._forward_event_shape_tensor(input_shape)<EOL><DEDENT>

Shape of a single sample from a single batch as an `int32` 1D `Tensor`.

        Args:
          input_shape: `Tensor`, `int32` vector indicating event-portion shape
            passed into `forward` function.
          name: name to give to the op

        Returns:
          forward_event_shape_tensor: `Tensor`, `int32` vector indicating
            event-portion shape after applying `forward`.


def __call__(self, value, name=None, **kwargs):

<EOL>from tensorflow_probability.python.bijectors import chain  <EOL>from tensorflow_probability.python.distributions import distribution  <EOL>from tensorflow_probability.python.distributions import transformed_distribution  <EOL>if type(value) is transformed_distribution.TransformedDistribution:  <EOL><INDENT>new_kwargs = value.parameters<EOL>new_kwargs.update(kwargs)<EOL>new_kwargs["<STR_LIT:name>"] = name or new_kwargs.get("<STR_LIT:name>", None)<EOL>new_kwargs["<STR_LIT>"] = self(value.bijector)<EOL>return transformed_distribution.TransformedDistribution(**new_kwargs)<EOL><DEDENT>if isinstance(value, distribution.Distribution):<EOL><INDENT>return transformed_distribution.TransformedDistribution(<EOL>distribution=value,<EOL>bijector=self,<EOL>name=name,<EOL>**kwargs)<EOL><DEDENT>if isinstance(value, chain.Chain):<EOL><INDENT>new_kwargs = kwargs.copy()<EOL>new_kwargs["<STR_LIT>"] = [self] + ([] if value.bijectors is None<EOL>else list(value.bijectors))<EOL>if "<STR_LIT>" not in new_kwargs:<EOL><INDENT>new_kwargs["<STR_LIT>"] = value.validate_args<EOL><DEDENT>new_kwargs["<STR_LIT:name>"] = name or value.name<EOL>return chain.Chain(**new_kwargs)<EOL><DEDENT>if isinstance(value, Bijector):<EOL><INDENT>return chain.Chain([self, value], name=name, **kwargs)<EOL><DEDENT>return self._call_forward(value, name=name or "<STR_LIT>", **kwargs)<EOL>

Applies or composes the `Bijector`, depending on input type.

        This is a convenience function which applies the `Bijector` instance in
        three different ways, depending on the input:

        1. If the input is a `tfd.Distribution` instance, return
           `tfd.TransformedDistribution(distribution=input, bijector=self)`.
        2. If the input is a `tfb.Bijector` instance, return
           `tfb.Chain([self, input])`.
        3. Otherwise, return `self.forward(input)`

        Args:
          value: A `tfd.Distribution`, `tfb.Bijector`, or a `Tensor`.
          name: Python `str` name given to ops created by this function.
          **kwargs: Additional keyword arguments passed into the created
            `tfd.TransformedDistribution`, `tfb.Bijector`, or `self.forward`.

        Returns:
          composition: A `tfd.TransformedDistribution` if the input was a
            `tfd.Distribution`, a `tfb.Chain` if the input was a `tfb.Bijector`, or
            a `Tensor` computed by `self.forward`.

        #### Examples

        ```python
        sigmoid = tfb.Reciprocal()(
            tfb.AffineScalar(shift=1.)(
              tfb.Exp()(
                tfb.AffineScalar(scale=-1.))))
        # ==> `tfb.Chain([
        #         tfb.Reciprocal(),
        #         tfb.AffineScalar(shift=1.),
        #         tfb.Exp(),
        #         tfb.AffineScalar(scale=-1.),
        #      ])`  # ie, `tfb.Sigmoid()`

        log_normal = tfb.Exp()(tfd.Normal(0, 1))
        # ==> `tfd.TransformedDistribution(tfd.Normal(0, 1), tfb.Exp())`

        tfb.Exp()([-1., 0., 1.])
        # ==> tf.exp([-1., 0., 1.])
        ```


with tf.compat.v2.name_scope(self.name):<EOL><INDENT>with tf.compat.v2.name_scope(name) as scope:<EOL><INDENT>yield scope<EOL><DEDENT><DEDENT>

Helper function to standardize op scope.


return self._call_forward_log_det_jacobian(x, event_ndims, name, **kwargs)<EOL>

Returns both the forward_log_det_jacobian.

        Args:
          x: `Tensor`. The input to the "forward" Jacobian determinant evaluation.
          event_ndims: Number of dimensions in the probabilistic events being
            transformed. Must be greater than or equal to
            `self.forward_min_event_ndims`. The result is summed over the final
            dimensions to produce a scalar Jacobian determinant for each event, i.e.
            it has shape `rank(x) - event_ndims` dimensions.
          name: The name to give this op.
          **kwargs: Named arguments forwarded to subclass implementation.

        Returns:
          `Tensor`, if this bijector is injective.
            If not injective this is not implemented.

        Raises:
          TypeError: if `self.dtype` is specified and `y.dtype` is not
            `self.dtype`.
          NotImplementedError: if neither `_forward_log_det_jacobian`
            nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or
            this is a non-injective bijector.


<EOL>return input_shape<EOL>

Subclass implementation for `forward_event_shape_tensor` function.


if mapping.x is not None and mapping.subkey in self._from_x[mapping.x]:<EOL><INDENT>self._cache_by_x(mapping)<EOL><DEDENT>if mapping.y is not None and mapping.subkey in self._from_y[mapping.y]:<EOL><INDENT>self._cache_by_y(mapping)<EOL><DEDENT>

Helper which updates only those cached entries that already exist.


raise NotImplementedError("<STR_LIT>")<EOL>

Subclass implementation for `inverse` public function.


return self._adjoint<EOL>

`bool` indicating `scale` should be used as conjugate transpose.


self._graph_parents = []<EOL>self._name = name<EOL>self._validate_args = validate_args<EOL>if scale_perturb_diag is not None and scale_perturb_factor is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self._is_only_identity_multiplier = (scale_tril is None and<EOL>scale_diag is None and<EOL>scale_perturb_factor is None)<EOL>with self._name_scope("<STR_LIT>"):<EOL><INDENT>if dtype is None:<EOL><INDENT>dtype = dtype_util.common_dtype([<EOL>shift, scale_identity_multiplier, scale_diag, scale_tril,<EOL>scale_perturb_diag, scale_perturb_factor<EOL>], tf.float32)<EOL><DEDENT>if shift is not None:<EOL><INDENT>shift = tf.convert_to_tensor(value=shift, name="<STR_LIT>", dtype=dtype)<EOL><DEDENT>self._shift = shift<EOL>if (self._is_only_identity_multiplier and<EOL>scale_identity_multiplier is None):<EOL><INDENT>scale_identity_multiplier = tf.convert_to_tensor(value=<NUM_LIT:1.>, dtype=dtype)<EOL><DEDENT>scale = self._create_scale_operator(<EOL>identity_multiplier=scale_identity_multiplier,<EOL>diag=scale_diag,<EOL>tril=scale_tril,<EOL>perturb_diag=scale_perturb_diag,<EOL>perturb_factor=scale_perturb_factor,<EOL>shift=shift,<EOL>validate_args=validate_args,<EOL>dtype=dtype)<EOL>if scale is not None and not self._is_only_identity_multiplier:<EOL><INDENT>if (shift is not None and<EOL>not dtype_util.base_equal(shift.dtype, scale.dtype)):<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>".format(<EOL>shift.dtype, scale.dtype))<EOL><DEDENT><DEDENT>self._scale = scale<EOL>self._adjoint = adjoint<EOL>super(Affine, self).__init__(<EOL>forward_min_event_ndims=<NUM_LIT:1>,<EOL>graph_parents=([self._scale] if tf.is_tensor(<EOL>self._scale) else self._scale.graph_parents +<EOL>[self._shift] if self._shift is not None else []),<EOL>is_constant_jacobian=True,<EOL>dtype=dtype,<EOL>validate_args=validate_args,<EOL>name=name)<EOL><DEDENT>

Instantiates the `Affine` bijector.

        This `Bijector` is initialized with `shift` `Tensor` and `scale` arguments,
        giving the forward operation:

        ```none
        Y = g(X) = scale @ X + shift
        ```

        where the `scale` term is logically equivalent to:

        ```python
        scale = (
          scale_identity_multiplier * tf.diag(tf.ones(d)) +
          tf.diag(scale_diag) +
          scale_tril +
          scale_perturb_factor @ diag(scale_perturb_diag) @
            tf.transpose([scale_perturb_factor])
        )
        ```

        If none of `scale_identity_multiplier`, `scale_diag`, or `scale_tril` are
        specified then `scale += IdentityMatrix`. Otherwise specifying a
        `scale` argument has the semantics of `scale += Expand(arg)`, i.e.,
        `scale_diag != None` means `scale += tf.diag(scale_diag)`.

        Args:
          shift: Floating-point `Tensor`. If this is set to `None`, no shift is
            applied.
          scale_identity_multiplier: floating point rank 0 `Tensor` representing a
            scaling done to the identity matrix.
            When `scale_identity_multiplier = scale_diag = scale_tril = None` then
            `scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added
            to `scale`.
          scale_diag: Floating-point `Tensor` representing the diagonal matrix.
            `scale_diag` has shape `[N1, N2, ...  k]`, which represents a k x k
            diagonal matrix.
            When `None` no diagonal term is added to `scale`.
          scale_tril: Floating-point `Tensor` representing the lower triangular
            matrix. `scale_tril` has shape `[N1, N2, ...  k, k]`, which represents a
            k x k lower triangular matrix.
            When `None` no `scale_tril` term is added to `scale`.
            The upper triangular elements above the diagonal are ignored.
          scale_perturb_factor: Floating-point `Tensor` representing factor matrix
            with last two dimensions of shape `(k, r)`. When `None`, no rank-r
            update is added to `scale`.
          scale_perturb_diag: Floating-point `Tensor` representing the diagonal
            matrix. `scale_perturb_diag` has shape `[N1, N2, ...  r]`, which
            represents an `r x r` diagonal matrix. When `None` low rank updates will
            take the form `scale_perturb_factor * scale_perturb_factor.T`.
          adjoint: Python `bool` indicating whether to use the `scale` matrix as
            specified or its adjoint.
            Default value: `False`.
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          name: Python `str` name given to ops managed by this object.
          dtype: `tf.DType` to prefer when converting args to `Tensor`s. Else, we
            fall back to a common dtype inferred from the args, finally falling back
            to float32.

        Raises:
          ValueError: if `perturb_diag` is specified but not `perturb_factor`.
          TypeError: if `shift` has different `dtype` from `scale` arguments.


if tensorshape_util.rank(x.shape) is not None:<EOL><INDENT>if tensorshape_util.rank(x.shape) == <NUM_LIT:1>:<EOL><INDENT>x = x[tf.newaxis, :]<EOL><DEDENT>return x<EOL><DEDENT>shape = tf.shape(input=x)<EOL>maybe_expanded_shape = tf.concat([<EOL>shape[:-<NUM_LIT:1>],<EOL>distribution_util.pick_vector(<EOL>tf.equal(tf.rank(x), <NUM_LIT:1>), [<NUM_LIT:1>], np.array([], dtype=np.int32)),<EOL>shape[-<NUM_LIT:1>:],<EOL>], <NUM_LIT:0>)<EOL>return tf.reshape(x, maybe_expanded_shape)<EOL>

Ensures non-scalar input has at least one column.

        Example:
          If `x = [1, 2, 3]` then the output is `[[1], [2], [3]]`.

          If `x = [[1, 2, 3], [4, 5, 6]]` then the output is unchanged.

          If `x = 1` then the output is unchanged.

        Args:
          x: `Tensor`.

        Returns:
          columnar_x: `Tensor` with at least two dimensions.


Instantiates the `TransformDiagonal` bijector.

        Args:
          diag_bijector: `Bijector` instance used to transform the diagonal.
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          name: Python `str` name given to ops managed by this object.


<EOL>super(Exp, self).__init__(<EOL>validate_args=validate_args,<EOL>name=name)<EOL>

Instantiates the `Exp` bijector.

        Args:
          validate_args: Python `bool` indicating whether arguments should be
            checked for correctness.
          name: Python `str` name given to ops managed by this object.


c = scale_identity_multiplier<EOL>d1 = scale_diag<EOL>tril = scale_tril<EOL>v = scale_perturb_factor<EOL>d2 = scale_perturb_diag<EOL>if v is None and d2 is not None:<EOL><INDENT>return None<EOL><DEDENT>if c is None and d1 is None and tril is None:<EOL><INDENT>c = <NUM_LIT:1.><EOL><DEDENT>matrix = np.float32(<NUM_LIT:0.>)<EOL>if c is not None:<EOL><INDENT>matrix += c * self._matrix_diag(np.ones_like(x))<EOL><DEDENT>if d1 is not None:<EOL><INDENT>matrix += self._matrix_diag(np.array(d1, dtype=np.float32))<EOL><DEDENT>if tril is not None:<EOL><INDENT>matrix += np.array(tril, dtype=np.float32)<EOL><DEDENT>if v is not None:<EOL><INDENT>v = np.array(v, dtype=np.float32)<EOL>if v.ndim < <NUM_LIT:2>:<EOL><INDENT>vt = v.T<EOL><DEDENT>else:<EOL><INDENT>vt = np.swapaxes(v, axis1=v.ndim - <NUM_LIT:2>, axis2=v.ndim - <NUM_LIT:1>)<EOL><DEDENT>if d2 is not None:<EOL><INDENT>d2 = self._matrix_diag(np.array(d2, dtype=np.float32))<EOL>right = np.matmul(d2, vt)<EOL><DEDENT>else:<EOL><INDENT>right = vt<EOL><DEDENT>matrix += np.matmul(v, right)<EOL><DEDENT>return matrix<EOL>

Create a scale matrix. Return None if it can not be created.


sqrt_eps = np.sqrt(np.finfo(dtype_util.as_numpy_dtype(x.dtype)).eps)<EOL>return tf.where(<EOL>tf.abs(x) * sqrt_eps <= <NUM_LIT:1.>,<EOL>tf.sqrt(x**<NUM_LIT> + <NUM_LIT:1.>),<EOL>tf.abs(x))<EOL>

Implementation of `sqrt(1 + x**2)` which is stable despite large `x`.


return self._shift<EOL>

The `shift` `Tensor` in `Y = scale @ X + shift`.


name = name or "<STR_LIT>"<EOL>with tf.compat.v2.name_scope(name):<EOL><INDENT>def _fn(x):<EOL><INDENT>"""<STR_LIT>"""<EOL>input_depth = tf.compat.dimension_value(<EOL>tensorshape_util.with_rank_at_least(x.shape, <NUM_LIT:1>)[-<NUM_LIT:1>])<EOL>if input_depth is None:<EOL><INDENT>raise NotImplementedError(<EOL>"<STR_LIT>")<EOL><DEDENT>input_shape = (<EOL>np.int32(tensorshape_util.as_list(x.shape))<EOL>if tensorshape_util.is_fully_defined(x.shape) else tf.shape(input=x))<EOL>if tensorshape_util.rank(x.shape) == <NUM_LIT:1>:<EOL><INDENT>x = x[tf.newaxis, ...]<EOL><DEDENT>for i, units in enumerate(hidden_layers):<EOL><INDENT>x = masked_dense(<EOL>inputs=x,<EOL>units=units,<EOL>num_blocks=input_depth,<EOL>exclusive=True if i == <NUM_LIT:0> else False,<EOL>activation=activation,<EOL>*args,  <EOL>**kwargs)<EOL><DEDENT>x = masked_dense(<EOL>inputs=x,<EOL>units=(<NUM_LIT:1> if shift_only else <NUM_LIT:2>) * input_depth,<EOL>num_blocks=input_depth,<EOL>activation=None,<EOL>*args,  <EOL>**kwargs)<EOL>if shift_only:<EOL><INDENT>x = tf.reshape(x, shape=input_shape)<EOL>return x, None<EOL><DEDENT>x = tf.reshape(x, shape=tf.concat([input_shape, [<NUM_LIT:2>]], axis=<NUM_LIT:0>))<EOL>shift, log_scale = tf.unstack(x, num=<NUM_LIT:2>, axis=-<NUM_LIT:1>)<EOL>which_clip = (<EOL>tf.clip_by_value<EOL>if log_scale_clip_gradient else clip_by_value_preserve_gradient)<EOL>log_scale = which_clip(log_scale, log_scale_min_clip, log_scale_max_clip)<EOL>return shift, log_scale<EOL><DEDENT>return tf.compat.v1.make_template(name, _fn)<EOL><DEDENT>

Build the Masked Autoregressive Density Estimator (Germain et al., 2015).

    This will be wrapped in a make_template to ensure the variables are only
    created once. It takes the input and returns the `loc` ("mu" in [Germain et
    al. (2015)][1]) and `log_scale` ("alpha" in [Germain et al. (2015)][1]) from
    the MADE network.

    Warning: This function uses `masked_dense` to create randomly initialized
    `tf.Variables`. It is presumed that these will be fit, just as you would any
    other neural architecture which uses `tf.layers.dense`.

    #### About Hidden Layers

    Each element of `hidden_layers` should be greater than the `input_depth`
    (i.e., `input_depth = tf.shape(input)[-1]` where `input` is the input to the
    neural network). This is necessary to ensure the autoregressivity property.

    #### About Clipping

    This function also optionally clips the `log_scale` (but possibly not its
    gradient). This is useful because if `log_scale` is too small/large it might
    underflow/overflow making it impossible for the `MaskedAutoregressiveFlow`
    bijector to implement a bijection. Additionally, the `log_scale_clip_gradient`
    `bool` indicates whether the gradient should also be clipped. The default does
    not clip the gradient; this is useful because it still provides gradient
    information (for fitting) yet solves the numerical stability problem. I.e.,
    `log_scale_clip_gradient = False` means
    `grad[exp(clip(x))] = grad[x] exp(clip(x))` rather than the usual
    `grad[clip(x)] exp(clip(x))`.

    Args:
      hidden_layers: Python `list`-like of non-negative integer, scalars
        indicating the number of units in each hidden layer. Default: `[512, 512].
      shift_only: Python `bool` indicating if only the `shift` term shall be
        computed. Default: `False`.
      activation: Activation function (callable). Explicitly setting to `None`
        implies a linear activation.
      log_scale_min_clip: `float`-like scalar `Tensor`, or a `Tensor` with the
        same shape as `log_scale`. The minimum value to clip by. Default: -5.
      log_scale_max_clip: `float`-like scalar `Tensor`, or a `Tensor` with the
        same shape as `log_scale`. The maximum value to clip by. Default: 3.
      log_scale_clip_gradient: Python `bool` indicating that the gradient of
        `tf.clip_by_value` should be preserved. Default: `False`.
      name: A name for ops managed by this function. Default:
        "masked_autoregressive_default_template".
      *args: `tf.layers.dense` arguments.
      **kwargs: `tf.layers.dense` keyword arguments.

    Returns:
      shift: `Float`-like `Tensor` of shift terms (the "mu" in
        [Germain et al.  (2015)][1]).
      log_scale: `Float`-like `Tensor` of log(scale) terms (the "alpha" in
        [Germain et al. (2015)][1]).

    Raises:
      NotImplementedError: if rightmost dimension of `inputs` is unknown prior to
        graph execution.

    #### References

    [1]: Mathieu Germain, Karol Gregor, Iain Murray, and Hugo Larochelle. MADE:
         Masked Autoencoder for Distribution Estimation. In _International
         Conference on Machine Learning_, 2015. https://arxiv.org/abs/1502.03509


initializer = tf.keras.initializers.get(initializer)<EOL>def masked_initializer(shape, dtype=None, partition_info=None):<EOL><INDENT>if partition_info is None:<EOL><INDENT>x = initializer(shape, dtype)<EOL><DEDENT>else:<EOL><INDENT>x = initializer(shape, dtype, partition_info)<EOL><DEDENT>return tf.cast(mask, x.dtype) * x<EOL><DEDENT>return masked_initializer<EOL>

Returns a masked version of the given initializer.


input_order = _create_input_order(input_size, input_order)<EOL>degrees = [input_order]<EOL>if hidden_units is None:<EOL><INDENT>hidden_units = []<EOL><DEDENT>for units in hidden_units:<EOL><INDENT>if isinstance(hidden_degrees, six.string_types):<EOL><INDENT>if hidden_degrees == "<STR_LIT>":<EOL><INDENT>degrees.append(<EOL>np.random.randint(low=min(np.min(degrees[-<NUM_LIT:1>]), input_size - <NUM_LIT:1>),<EOL>high=input_size,<EOL>size=units))<EOL><DEDENT>elif hidden_degrees == "<STR_LIT>":<EOL><INDENT>min_degree = min(np.min(degrees[-<NUM_LIT:1>]), input_size - <NUM_LIT:1>)<EOL>degrees.append(np.maximum(<EOL>min_degree,<EOL>np.ceil(np.arange(<NUM_LIT:1>, units + <NUM_LIT:1>)<EOL>* (input_size - <NUM_LIT:1>) / float(units + <NUM_LIT:1>)).astype(np.int32)))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(hidden_degrees))<EOL><DEDENT><DEDENT>return degrees<EOL>

Returns a list of degree vectors, one for each input and hidden layer.

    A unit with degree d can only receive input from units with degree < d. Output
    units always have the same degree as their associated input unit.

    Args:
      input_size: Number of inputs.
      hidden_units: list with the number of hidden units per layer. It does not
        include the output layer. Each hidden unit size must be at least the size
        of length (otherwise autoregressivity is not possible).
      input_order: Order of degrees to the input units: 'random', 'left-to-right',
        'right-to-left', or an array of an explicit order. For example,
        'left-to-right' builds an autoregressive model
        p(x) = p(x1) p(x2 | x1) ... p(xD | x<D).
      hidden_degrees: Method for assigning degrees to the hidden units:
        'equal', 'random'.  If 'equal', hidden units in each layer are allocated
        equally (up to a remainder term) to each degree.  Default: 'equal'.

    Raises:
      ValueError: invalid input order.
      ValueError: invalid hidden degrees.


def _gen_slices(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE):

<EOL>slices = []<EOL>col = <NUM_LIT:0><EOL>d_in = n_in // num_blocks<EOL>d_out = n_out // num_blocks<EOL>row = d_out if mask_type == MASK_EXCLUSIVE else <NUM_LIT:0><EOL>for _ in range(num_blocks):<EOL><INDENT>row_slice = slice(row, None)<EOL>col_slice = slice(col, col + d_in)<EOL>slices.append([row_slice, col_slice])<EOL>col += d_in<EOL>row += d_out<EOL><DEDENT>return slices<EOL>

Generate the slices for building an autoregressive mask.


if inverse_event_ndims is None:<EOL><INDENT>inverse_event_ndims = event_ndims<EOL><DEDENT>assert_finite(x)<EOL>assert_finite(y)<EOL>f_x = bijector.forward(x)<EOL>g_y = bijector.inverse(y)<EOL>[<EOL>x_from_x,<EOL>y_from_y,<EOL>ildj_f_x,<EOL>fldj_x,<EOL>ildj_y,<EOL>fldj_g_y,<EOL>f_x_v,<EOL>g_y_v,<EOL>] = eval_func([<EOL>bijector.inverse(f_x),<EOL>bijector.forward(g_y),<EOL>bijector.inverse_log_det_jacobian(f_x, event_ndims=inverse_event_ndims),<EOL>bijector.forward_log_det_jacobian(x, event_ndims=event_ndims),<EOL>bijector.inverse_log_det_jacobian(y, event_ndims=inverse_event_ndims),<EOL>bijector.forward_log_det_jacobian(g_y, event_ndims=event_ndims),<EOL>f_x,<EOL>g_y,<EOL>])<EOL>assert_finite(x_from_x)<EOL>assert_finite(y_from_y)<EOL>assert_finite(ildj_f_x)<EOL>assert_finite(fldj_x)<EOL>assert_finite(ildj_y)<EOL>assert_finite(fldj_g_y)<EOL>assert_finite(f_x_v)<EOL>assert_finite(g_y_v)<EOL>np.testing.assert_allclose(x_from_x, x, atol=atol, rtol=rtol)<EOL>np.testing.assert_allclose(y_from_y, y, atol=atol, rtol=rtol)<EOL>np.testing.assert_allclose(-ildj_f_x, fldj_x, atol=atol, rtol=rtol)<EOL>np.testing.assert_allclose(-ildj_y, fldj_g_y, atol=atol, rtol=rtol)<EOL>

Assert that forward/inverse (along with jacobians) are inverses and finite.

    It is recommended to use x and y values that are very very close to the edge
    of the Bijector's domain.

    Args:
      bijector:  A Bijector instance.
      x:  np.array of values in the domain of bijector.forward.
      y:  np.array of values in the domain of bijector.inverse.
      event_ndims: Integer describing the number of event dimensions this bijector
        operates on.
      eval_func: Function to evaluate any intermediate results.
      inverse_event_ndims: Integer describing the number of event dimensions for
        the bijector codomain. If None, then the value of `event_ndims` is used.
      atol:  Absolute tolerance.
      rtol:  Relative tolerance.

    Raises:
      AssertionError:  If tests fail.


<EOL>ten_x_pts = np.linspace(lower_x, upper_x, num=<NUM_LIT:10>).astype(np.float32)<EOL>if bijector.dtype is not None:<EOL><INDENT>ten_x_pts = ten_x_pts.astype(dtype_util.as_numpy_dtype(bijector.dtype))<EOL><DEDENT>forward_on_10_pts = bijector.forward(ten_x_pts)<EOL>lower_y, upper_y = eval_func(<EOL>[bijector.forward(lower_x),<EOL>bijector.forward(upper_x)])<EOL>if upper_y < lower_y:  <EOL><INDENT>lower_y, upper_y = upper_y, lower_y<EOL><DEDENT>uniform_x_samps = uniform_distribution.Uniform(<EOL>low=lower_x, high=upper_x).sample(<EOL>n, seed=<NUM_LIT:0>)<EOL>uniform_y_samps = uniform_distribution.Uniform(<EOL>low=lower_y, high=upper_y).sample(<EOL>n, seed=<NUM_LIT:1>)<EOL>inverse_forward_x = bijector.inverse(bijector.forward(uniform_x_samps))<EOL>forward_inverse_y = bijector.forward(bijector.inverse(uniform_y_samps))<EOL>dy_dx = tf.exp(<EOL>bijector.inverse_log_det_jacobian(uniform_y_samps, event_ndims=<NUM_LIT:0>))<EOL>expectation_of_dy_dx_under_uniform = tf.reduce_mean(input_tensor=dy_dx)<EOL>change_measure_dy_dx = (<EOL>(upper_y - lower_y) * expectation_of_dy_dx_under_uniform)<EOL>dx_dy = tf.exp(<EOL>bijector.forward_log_det_jacobian(<EOL>bijector.inverse(uniform_y_samps), event_ndims=<NUM_LIT:0>))<EOL>[<EOL>forward_on_10_pts_v,<EOL>dy_dx_v,<EOL>dx_dy_v,<EOL>change_measure_dy_dx_v,<EOL>uniform_x_samps_v,<EOL>uniform_y_samps_v,<EOL>inverse_forward_x_v,<EOL>forward_inverse_y_v,<EOL>] = eval_func([<EOL>forward_on_10_pts,<EOL>dy_dx,<EOL>dx_dy,<EOL>change_measure_dy_dx,<EOL>uniform_x_samps,<EOL>uniform_y_samps,<EOL>inverse_forward_x,<EOL>forward_inverse_y,<EOL>])<EOL>assert_strictly_monotonic(forward_on_10_pts_v)<EOL>np.testing.assert_allclose(<EOL>inverse_forward_x_v, uniform_x_samps_v, atol=<NUM_LIT>, rtol=<NUM_LIT>)<EOL>np.testing.assert_allclose(<EOL>forward_inverse_y_v, uniform_y_samps_v, atol=<NUM_LIT>, rtol=<NUM_LIT>)<EOL>np.testing.assert_allclose(<EOL>upper_x - lower_x, change_measure_dy_dx_v, atol=<NUM_LIT:0>, rtol=rtol)<EOL>np.testing.assert_allclose(<EOL>dy_dx_v, np.divide(<NUM_LIT:1.>, dx_dy_v), atol=<NUM_LIT>, rtol=<NUM_LIT>)<EOL>

Assert `bijector`'s forward/inverse/inverse_log_det_jacobian are congruent.

    We draw samples `X ~ U(lower_x, upper_x)`, then feed these through the
    `bijector` in order to check that:

    1. the forward is strictly monotonic.
    2. the forward/inverse methods are inverses of each other.
    3. the jacobian is the correct change of measure.

    This can only be used for a Bijector mapping open subsets of the real line
    to themselves.  This is due to the fact that this test compares the `prob`
    before/after transformation with the Lebesgue measure on the line.

    Args:
      bijector:  Instance of Bijector
      lower_x:  Python scalar.
      upper_x:  Python scalar.  Must have `lower_x < upper_x`, and both must be in
        the domain of the `bijector`.  The `bijector` should probably not produce
        huge variation in values in the interval `(lower_x, upper_x)`, or else the
        variance based check of the Jacobian will require small `rtol` or huge
        `n`.
      eval_func: Function to evaluate any intermediate results.
      n:  Number of samples to draw for the checks.
      rtol:  Positive number.  Used for the Jacobian check.

    Raises:
      AssertionError:  If tests fail.


return self._slope_scale<EOL>

Standard deviation of the slope transitions.


return self._observation_noise_scale<EOL>

Standard deviation of the observation noise.


ndarray = np.asarray(ndarray).astype(self.dtype)<EOL>return tf.compat.v1.placeholder_with_default(<EOL>input=ndarray, shape=ndarray.shape if self.use_static_shape else None)<EOL>

Convert a numpy array to a TF placeholder.

        Args:
          ndarray: any object convertible to a numpy array via `np.asarray()`.

        Returns:
          placeholder: a TensorFlow `placeholder` with default value given by the
          provided `ndarray`, dtype given by `self.dtype`, and shape specified
          statically only if `self.use_static_shape` is `True`.


top_row = tf.expand_dims(coefficients, -<NUM_LIT:2>)<EOL>coef_shape = dist_util.prefer_static_shape(coefficients)<EOL>batch_shape, order = coef_shape[:-<NUM_LIT:1>], coef_shape[-<NUM_LIT:1>]<EOL>remaining_rows = tf.concat([<EOL>tf.eye(order - <NUM_LIT:1>, dtype=coefficients.dtype, batch_shape=batch_shape),<EOL>tf.zeros(tf.concat([batch_shape, (order - <NUM_LIT:1>, <NUM_LIT:1>)], axis=<NUM_LIT:0>),<EOL>dtype=coefficients.dtype)<EOL>], axis=-<NUM_LIT:1>)<EOL>ar_matrix = tf.concat([top_row, remaining_rows], axis=-<NUM_LIT:2>)<EOL>return ar_matrix<EOL>

Build transition matrix for an autoregressive StateSpaceModel.

    When applied to a vector of previous values, this matrix computes
    the expected new value (summing the previous states according to the
    autoregressive coefficients) in the top dimension of the state space,
    and moves all previous values down by one dimension, 'forgetting' the
    final (least recent) value. That is, it looks like this:

    ```
    ar_matrix = [ coefs[0], coefs[1], ..., coefs[order]
                  1.,       0 ,       ..., 0.
                  0.,       1.,       ..., 0.
                  ...
                  0.,       0.,  ..., 1.,  0.            ]
    ```

    Args:
      coefficients: float `Tensor` of shape `concat([batch_shape, [order]])`.

    Returns:
      ar_matrix: float `Tensor` with shape `concat([batch_shape,
      [order, order]])`.


with tf.compat.v1.name_scope(<EOL>name, '<STR_LIT>', values=[observed_time_series]) as name:<EOL><INDENT>masked_time_series = None<EOL>if observed_time_series is not None:<EOL><INDENT>masked_time_series = (<EOL>sts_util.canonicalize_observed_time_series_with_mask(<EOL>observed_time_series))<EOL><DEDENT>dtype = dtype_util.common_dtype(<EOL>[(masked_time_series.time_series<EOL>if masked_time_series is not None else None),<EOL>coefficients_prior,<EOL>level_scale_prior,<EOL>initial_state_prior], preferred_dtype=tf.float32)<EOL>if observed_time_series is not None:<EOL><INDENT>_, observed_stddev, observed_initial = sts_util.empirical_statistics(<EOL>masked_time_series)<EOL><DEDENT>else:<EOL><INDENT>observed_stddev, observed_initial = (<EOL>tf.convert_to_tensor(value=<NUM_LIT:1.>, dtype=dtype),<EOL>tf.convert_to_tensor(value=<NUM_LIT:0.>, dtype=dtype))<EOL><DEDENT>batch_ones = tf.ones(tf.concat([<EOL>tf.shape(input=observed_initial),  <EOL>[order]], axis=<NUM_LIT:0>), dtype=dtype)<EOL>if coefficients_prior is None:<EOL><INDENT>coefficients_prior = tfd.MultivariateNormalDiag(<EOL>scale_diag=batch_ones)<EOL><DEDENT>if level_scale_prior is None:<EOL><INDENT>level_scale_prior = tfd.LogNormal(<EOL>loc=tf.math.log(<NUM_LIT> *  observed_stddev), scale=<NUM_LIT>)<EOL><DEDENT>if (coefficients_prior.event_shape.is_fully_defined() and<EOL>order != coefficients_prior.event_shape[<NUM_LIT:0>]):<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>coefficients_prior.event_shape[<NUM_LIT:0>], order))<EOL><DEDENT>if initial_state_prior is None:<EOL><INDENT>initial_state_prior = tfd.MultivariateNormalDiag(<EOL>loc=observed_initial[..., tf.newaxis] * batch_ones,<EOL>scale_diag=(tf.abs(observed_initial) +<EOL>observed_stddev)[..., tf.newaxis] * batch_ones)<EOL><DEDENT>self._order = order<EOL>self._coefficients_prior = coefficients_prior<EOL>self._level_scale_prior = level_scale_prior<EOL>self._initial_state_prior = initial_state_prior<EOL>if coefficient_constraining_bijector is None:<EOL><INDENT>coefficient_constraining_bijector = tfb.Tanh()<EOL><DEDENT>super(Autoregressive, self).__init__(<EOL>parameters=[<EOL>Parameter('<STR_LIT>',<EOL>coefficients_prior,<EOL>coefficient_constraining_bijector),<EOL>Parameter('<STR_LIT>', level_scale_prior, tfb.Softplus())<EOL>],<EOL>latent_size=order,<EOL>name=name)<EOL><DEDENT>

Specify an autoregressive model.

        Args:
          order: scalar Python positive `int` specifying the number of past
            timesteps to regress on.
          coefficients_prior: optional `tfd.Distribution` instance specifying a
            prior on the `coefficients` parameter. If `None`, a default standard
            normal (`tfd.MultivariateNormalDiag(scale_diag=tf.ones([order]))`) prior
            is used.
            Default value: `None`.
          level_scale_prior: optional `tfd.Distribution` instance specifying a prior
            on the `level_scale` parameter. If `None`, a heuristic default prior is
            constructed based on the provided `observed_time_series`.
            Default value: `None`.
          initial_state_prior: optional `tfd.Distribution` instance specifying a
            prior on the initial state, corresponding to the values of the process
            at a set of size `order` of imagined timesteps before the initial step.
            If `None`, a heuristic default prior is constructed based on the
            provided `observed_time_series`.
            Default value: `None`.
          coefficient_constraining_bijector: optional `tfb.Bijector` instance
            representing a constraining mapping for the autoregressive coefficients.
            For example, `tfb.Tanh()` constrains the coefficients to lie in
            `(-1, 1)`, while `tfb.Softplus()` constrains them to be positive, and
            `tfb.Identity()` implies no constraint. If `None`, the default behavior
            constrains the coefficients to lie in `(-1, 1)` using a `Tanh` bijector.
            Default value: `None`.
          observed_time_series: optional `float` `Tensor` of shape
            `batch_shape + [T, 1]` (omitting the trailing unit dimension is also
            supported when `T > 1`), specifying an observed time series.
            Any priors not explicitly set will be given default values according to
            the scale of the observed time series (or batch of time series). May
            optionally be an instance of `tfp.sts.MaskedTimeSeries`, which includes
            a mask `Tensor` to specify timesteps with missing observations.
            Default value: `None`.
          name: the name of this model component.
            Default value: 'Autoregressive'.


with tf.compat.v1.name_scope(<EOL>'<STR_LIT>', values=[observed_time_series_tensor]):<EOL><INDENT>if (observed_time_series_tensor.shape.ndims is not None and<EOL>tf.compat.dimension_value(<EOL>observed_time_series_tensor.shape[-<NUM_LIT:1>]) is not None):<EOL><INDENT>expanded_time_series = (<EOL>observed_time_series_tensor<EOL>if observed_time_series_tensor.shape[-<NUM_LIT:1>] == <NUM_LIT:1><EOL>else observed_time_series_tensor[..., tf.newaxis])<EOL><DEDENT>else:<EOL><INDENT>expanded_time_series = tf.cond(<EOL>pred=tf.equal(tf.shape(input=observed_time_series_tensor)[-<NUM_LIT:1>], <NUM_LIT:1>),<EOL>true_fn=lambda: observed_time_series_tensor,<EOL>false_fn=lambda: observed_time_series_tensor[..., tf.newaxis])<EOL><DEDENT>return expanded_time_series<EOL><DEDENT>

Ensures `observed_time_series_tensor` has a trailing dimension of size 1.

    The `tfd.LinearGaussianStateSpaceModel` Distribution has event shape of
    `[num_timesteps, observation_size]`, but canonical BSTS models
    are univariate, so their observation_size is always `1`. The extra trailing
    dimension gets annoying, so this method allows arguments with or without the
    extra dimension. There is no ambiguity except in the trivial special case
    where  `num_timesteps = 1`; this can be avoided by specifying any unit-length
    series in the explicit `[num_timesteps, 1]` style.

    Most users should not call this method directly, and instead call
    `canonicalize_observed_time_series_with_mask`, which handles converting
    to `Tensor` and specifying an optional missingness mask.

    Args:
      observed_time_series_tensor: `Tensor` of shape
        `batch_shape + [num_timesteps, 1]` or `batch_shape + [num_timesteps]`,
        where `num_timesteps > 1`.

    Returns:
      expanded_time_series: `Tensor` of shape `batch_shape + [num_timesteps, 1]`.


graph_parents = [tensor for distribution in distributions<EOL>for tensor in distribution._graph_parents]  <EOL>with tf.compat.v1.name_scope('<STR_LIT>', values=graph_parents):<EOL><INDENT>if all([isinstance(mvn, tfd.MultivariateNormalDiag)<EOL>for mvn in distributions]):<EOL><INDENT>return tfd.MultivariateNormalDiag(<EOL>loc=sum([mvn.mean() for mvn in distributions]),<EOL>scale_diag=tf.sqrt(sum([<EOL>mvn.scale.diag**<NUM_LIT:2> for mvn in distributions])))<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(distributions))<EOL><DEDENT><DEDENT>

Attempt to sum MultivariateNormal distributions.

    The sum of (multivariate) normal random variables is itself (multivariate)
    normal, with mean given by the sum of means and (co)variance given by the
    sum of (co)variances. This method exploits this fact to compute the
    sum of a list of `tfd.MultivariateNormalDiag` objects.

    It may in the future be extended to support summation of other forms of
    (Multivariate)Normal distributions.

    Args:
      distributions: Python `iterable` of `tfd.MultivariateNormalDiag`
        distribution instances. These must all have the same event
        shape, and broadcast to a consistent batch shape.

    Returns:
      sum_distribution: A `tfd.MultivariateNormalDiag` instance with mean
        equal to the sum of input means and covariance equal to the sum of
        input covariances.


with tf.compat.v1.name_scope('<STR_LIT>'):<EOL><INDENT>if hasattr(maybe_masked_observed_time_series, '<STR_LIT>'):<EOL><INDENT>observed_time_series = (<EOL>maybe_masked_observed_time_series.time_series)<EOL>is_missing = maybe_masked_observed_time_series.is_missing<EOL><DEDENT>else:<EOL><INDENT>observed_time_series = maybe_masked_observed_time_series<EOL>is_missing = None<EOL><DEDENT>observed_time_series = tf.convert_to_tensor(value=observed_time_series,<EOL>name='<STR_LIT>')<EOL>observed_time_series = _maybe_expand_trailing_dim(observed_time_series)<EOL>if is_missing is not None:<EOL><INDENT>is_missing = tf.convert_to_tensor(<EOL>value=is_missing, name='<STR_LIT>', dtype_hint=tf.bool)<EOL><DEDENT>return missing_values_util.MaskedTimeSeries(observed_time_series,<EOL>is_missing=is_missing)<EOL><DEDENT>

Extract a Tensor with canonical shape and optional mask.

    Args:
      maybe_masked_observed_time_series: a `Tensor`-like object with shape
        `[..., num_timesteps]` or `[..., num_timesteps, 1]`, or a
        `tfp.sts.MaskedTimeSeries` containing such an object.
    Returns:
      masked_time_series: a `tfp.sts.MaskedTimeSeries` namedtuple, in which
        the `observed_time_series` is converted to `Tensor` with canonical shape
        `[..., num_timesteps, 1]`, and `is_missing` is either `None` or a boolean
        `Tensor`.