Add condtion.

        Args:
            observed_arr:       `np.ndarray` of samples.

        Returns:
            `np.ndarray` of samples.
778035
def add_condition(self, observed_arr):
        '''
        
        '''
        condition_arr = self.__image_true_sampler.draw()
        return np.concatenate((observed_arr, condition_arr), axis=1)
249602
def _maybe_fill(arr, fill_value=np.nan):
    
    if _isna_compat(arr, fill_value):
        arr.fill(fill_value)
    return arr
266312
def observed_data_to_xarray(self):
        """"""
        observed_data_raw = _read_data(self.observed_data)
        variables = self.observed_data_var
        if isinstance(variables, str):
            variables = [variables]
        observed_data = {}
        for key, vals in observed_data_raw.items():
            if variables is not None and key not in variables:
                continue
            vals = np.atleast_1d(vals)
            val_dims = self.dims.get(key)
            val_dims, coords = generate_dims_coords(
                vals.shape, key, dims=val_dims, coords=self.coords
            )
            observed_data[key] = xr.DataArray(vals, dims=val_dims, coords=coords)
        return xr.Dataset(data_vars=observed_data)
1186009
def insert_at(df, sample_date, values):
    
    observed_dt = dt(datetime.now())
    return multi_index_insert_row(df, [sample_date, observed_dt], values)
1020302
def sample_observed_state(self, s: pd.Series) -> Dict:
        

        return {
            n[0]: {
                i.name: np.random.normal(s[n[0]] * i.mean, i.stdev)
                for i in n[1]["indicators"].values()
            }
            for n in self.nodes(data=True)
        }
735952
def draw(self):
        '''
        
        '''
        observed_arr = self.extract_conditions()
        conv_arr = self.inference(observed_arr)

        if self.__conditon_noise_sampler is not None:
            self.__conditon_noise_sampler.output_shape = conv_arr.shape
            noise_arr = self.__conditon_noise_sampler.generate()
            conv_arr += noise_arr

        deconv_arr = self.__deconvolution_model.inference(conv_arr)
        return np.concatenate((deconv_arr, observed_arr), axis=1)
1190014
def inference(self, observed_arr):
        '''
        
        '''
        decoded_arr = self.__encoder_decoder_controller.inference(observed_arr)
        encoded_arr = self.__encoder_decoder_controller.get_feature_points()
        _ = self.__retrospective_encoder.inference(decoded_arr)
        re_encoded_arr = self.__retrospective_encoder.get_feature_points()
        self.__inferenced_tuple = (observed_arr, encoded_arr, decoded_arr, re_encoded_arr)
        return re_encoded_arr
877293
def observed(func):
    

    def wrapper(*args, **kwargs):
        self = args[0]
        assert(isinstance(self, Observable))

        self._notify_method_before(self, func.__name__, args, kwargs)
        res = func(*args, **kwargs)
        self._notify_method_after(self, func.__name__, res, args, kwargs)
        return res

    log.logger.warning("Decorator observable.observed is deprecated:"
                       "use Observable.observed instead")
    return wrapper
220736
def asarray_ndim(a, *ndims, **kwargs):
    
    allow_none = kwargs.pop('allow_none', False)
    kwargs.setdefault('copy', False)
    if a is None and allow_none:
        return None
    a = np.array(a, **kwargs)
    if a.ndim not in ndims:
        if len(ndims) > 1:
            expect_str = 'one of %s' % str(ndims)
        else:
            # noinspection PyUnresolvedReferences
            expect_str = '%s' % ndims[0]
        raise TypeError('bad number of dimensions: expected %s; found %s' %
                        (expect_str, a.ndim))
    return a
325172
def generate(self):
        '''
        
        '''
        observed_arr = None
        for row in range(self.__batch_size):
            arr = None
            for d in range(self.__dim):
                _arr = self.__generate_sin(
                    amp=self.__amp,
                    sampling_freq=self.__sampling_freq,
                    freq=self.__freq,
                    sec=self.__sec,
                    seq_len=self.__seq_len
                )
                _arr = np.expand_dims(_arr, axis=0)
                if arr is None:
                    arr = _arr
                else:
                    arr = np.r_[arr, _arr]

            arr = np.expand_dims(arr, axis=0)

            if observed_arr is None:
                observed_arr = arr
            else:
                observed_arr = np.r_[observed_arr, arr]

        observed_arr = observed_arr.transpose((0, 2, 1))
        gauss_noise = np.random.normal(loc=self.__mu, scale=self.__sigma, size=observed_arr.shape)
        observed_arr = observed_arr + gauss_noise
        if self.noise_sampler is not None:
            self.noise_sampler.output_shape = observed_arr.shape
            observed_arr += self.noise_sampler.generate()

        if self.__norm_mode == "z_score":
            if observed_arr.std() != 0:
                observed_arr = (observed_arr - observed_arr.mean()) / observed_arr.std()
        elif self.__norm_mode == "min_max":
            if (observed_arr.max() - observed_arr.min()) != 0:
                observed_arr = (observed_arr - observed_arr.min()) / (observed_arr.max() - observed_arr.min())
        elif self.__norm_mode == "tanh":
            observed_arr = np.tanh(observed_arr)

        return observed_arr
1077116
def add_or_update_records(cls, tables: I2B2Tables, records: List["ObservationFact"]) -> Tuple[int, int]:
        
        return cls._add_or_update_records(tables.crc_connection, tables.observation_fact, records)
245082
def draw(self):
        '''
        
        '''
        observed_arr = None
        for result_tuple in self.__feature_generator.generate():
            observed_arr = result_tuple[0]
            break

        observed_arr = observed_arr.astype(float)
        if self.__norm_mode == "z_score":
            if observed_arr.std() != 0:
                observed_arr = (observed_arr - observed_arr.mean()) / observed_arr.std()
        elif self.__norm_mode == "min_max":
            if (observed_arr.max() - observed_arr.min()) != 0:
                observed_arr = (observed_arr - observed_arr.min()) / (observed_arr.max() - observed_arr.min())
        elif self.__norm_mode == "tanh":
            observed_arr = np.tanh(observed_arr)

        return observed_arr
566906
def inference(self, observed_arr):
        '''
        
        '''
        for i in range(len(self.__deconvolution_layer_list)):
            try:
                observed_arr = self.__deconvolution_layer_list[i].forward_propagate(observed_arr)
            except:
                self.__logger.debug("Error raised in Deconvolution layer " + str(i + 1))
                raise

        return observed_arr
237044
def learn(self, observed_arr, target_arr):
        '''
        
        '''
        # Pre-learning.
        if self.__pre_learning_epochs > 0:
            self.__encoder_decoder_controller.learn(observed_arr, observed_arr)

        learning_rate = self.__learning_rate
        row_o = observed_arr.shape[0]
        row_t = target_arr.shape[0]
        if row_t != 0 and row_t != row_o:
            raise ValueError("The row of `target_arr` must be equivalent to the row of `observed_arr`.")

        if row_t == 0:
            target_arr = observed_arr.copy()
        else:
            if target_arr.ndim == 2:
                target_arr = target_arr.reshape((target_arr.shape[0], 1, target_arr.shape[1]))

        if self.__test_size_rate > 0:
            train_index = np.random.choice(observed_arr.shape[0], round((1 - self.__test_size_rate) * observed_arr.shape[0]), replace=False)
            test_index = np.array(list(set(range(observed_arr.shape[0])) - set(train_index)))
            train_observed_arr = observed_arr[train_index]
            test_observed_arr = observed_arr[test_index]
            train_target_arr = target_arr[train_index]
            test_target_arr = target_arr[test_index]
        else:
            train_observed_arr = observed_arr
            train_target_arr = target_arr

        encoder_best_params_list = []
        decoder_best_params_list = []
        re_encoder_best_params_list = []
        try:
            self.__change_inferencing_mode(False)
            self.__memory_tuple_list = []
            eary_stop_flag = False
            loss_list = []
            min_loss = None
            for epoch in range(self.__epochs):
                if ((epoch + 1) % self.__attenuate_epoch == 0):
                    learning_rate = learning_rate / self.__learning_attenuate_rate

                rand_index = np.random.choice(train_observed_arr.shape[0], size=self.__batch_size)
                batch_observed_arr = train_observed_arr[rand_index]
                batch_target_arr = train_target_arr[rand_index]
                try:
                    _ = self.inference(batch_observed_arr)
                    delta_arr, _, loss = self.compute_retrospective_loss()

                    remember_flag = False
                    if len(loss_list) > 0:
                        if abs(loss - (sum(loss_list)/len(loss_list))) > self.__tld:
                            remember_flag = True

                    if remember_flag is True:
                        self.__remember_best_params(
                            encoder_best_params_list,
                            decoder_best_params_list,
                            re_encoder_best_params_list
                        )
                        # Re-try.
                        _ = self.inference(batch_observed_arr)
                        delta_arr, _, loss = self.compute_retrospective_loss()

                    re_encoder_grads_list, decoder_grads_list, encoder_delta_arr, encoder_grads_list = self.back_propagation(delta_arr)
                    self.optimize(
                        re_encoder_grads_list,
                        decoder_grads_list, 
                        encoder_grads_list, 
                        learning_rate, 
                        epoch
                    )

                    if min_loss is None or min_loss > loss:
                        min_loss = loss
                        
                        encoder_best_params_list = [
                            self.__encoder_decoder_controller.encoder.graph.weights_lstm_hidden_arr,
                            self.__encoder_decoder_controller.encoder.graph.weights_lstm_observed_arr,
                            self.__encoder_decoder_controller.encoder.graph.lstm_bias_arr
                        ]
                        decoder_best_params_list = [
                            self.__encoder_decoder_controller.decoder.graph.weights_lstm_hidden_arr,
                            self.__encoder_decoder_controller.decoder.graph.weights_lstm_observed_arr,
                            self.__encoder_decoder_controller.decoder.graph.lstm_bias_arr
                        ]
                        re_encoder_best_params_list = [
                            self.__retrospective_encoder.graph.weights_lstm_hidden_arr,
                            self.__retrospective_encoder.graph.weights_lstm_observed_arr,
                            self.__retrospective_encoder.graph.lstm_bias_arr
                        ]
                        self.__logger.debug("Best params are updated.")

                    self.__encoder_decoder_controller.encoder.graph.hidden_activity_arr = np.array([])
                    self.__encoder_decoder_controller.encoder.graph.cec_activity_arr = np.array([])
                    self.__encoder_decoder_controller.decoder.graph.hidden_activity_arr = np.array([])
                    self.__encoder_decoder_controller.decoder.graph.cec_activity_arr = np.array([])
                    self.__retrospective_encoder.graph.hidden_activity_arr = np.array([])
                    self.__retrospective_encoder.graph.cec_activity_arr = np.array([])

                except FloatingPointError:
                    if epoch > int(self.__epochs * 0.7):
                        self.__logger.debug(
                            "Underflow occurred when the parameters are being updated. Because of early stopping, this error is catched and the parameter is not updated."
                        )
                        eary_stop_flag = True
                        break
                    else:
                        self.__logger.debug(
                            "Underflow occurred when the parameters are being updated."
                        )
                        raise

                if self.__test_size_rate > 0:
                    rand_index = np.random.choice(test_observed_arr.shape[0], size=self.__batch_size)
                    test_batch_observed_arr = test_observed_arr[rand_index]
                    test_batch_target_arr = test_target_arr[rand_index]

                    self.__change_inferencing_mode(True)
                    _ = self.inference(test_batch_observed_arr)
                    _, _, test_loss = self.compute_retrospective_loss()

                    remember_flag = False
                    if len(loss_list) > 0:
                        if abs(test_loss - (sum(loss_list)/len(loss_list))) > self.__tld:
                            remember_flag = True

                    if remember_flag is True:
                        self.__remember_best_params(
                            encoder_best_params_list, 
                            decoder_best_params_list,
                            re_encoder_best_params_list
                        )
                        # Re-try.
                        _ = self.inference(test_batch_observed_arr)
                        _, _, test_loss = self.compute_retrospective_loss()

                    self.__change_inferencing_mode(False)

                    self.__verificate_retrospective_loss(loss, test_loss)

                self.__encoder_decoder_controller.encoder.graph.hidden_activity_arr = np.array([])
                self.__encoder_decoder_controller.encoder.graph.cec_activity_arr = np.array([])
                self.__encoder_decoder_controller.decoder.graph.hidden_activity_arr = np.array([])
                self.__encoder_decoder_controller.decoder.graph.cec_activity_arr = np.array([])

                if epoch > 1 and abs(loss - loss_list[-1]) < self.__tol:
                    eary_stop_flag = True
                    break
                loss_list.append(loss)

        except KeyboardInterrupt:
            self.__logger.debug("Interrupt.")

        if eary_stop_flag is True:
            self.__logger.debug("Early stopping.")
            eary_stop_flag = False
        
        self.__remember_best_params(
            encoder_best_params_list, 
            decoder_best_params_list,
            re_encoder_best_params_list
        )
        self.__change_inferencing_mode(True)
        self.__logger.debug("end. ")
1207220
def augment_observation(
    observation, reward, cum_reward, frame_index, bar_color=None,
    header_height=27
):
  """"""
  img = PIL_Image().new(
      "RGB", (observation.shape[1], header_height,)
  )
  draw = PIL_ImageDraw().Draw(img)
  draw.text(
      (1, 0), "c:{:3}, r:{:3}".format(int(cum_reward), int(reward)),
      fill=(255, 0, 0)
  )
  draw.text(
      (1, 15), "f:{:3}".format(int(frame_index)),
      fill=(255, 0, 0)
  )
  header = np.copy(np.asarray(img))
  del img
  if bar_color is not None:
    header[0, :, :] = bar_color
  return np.concatenate([header, observation], axis=0)
1127760
def add_observation(self, obs):
        
        if len(self._observations)==0:
            self._observations.append(obs)
        else:
            res = obs.resolution
            ind = 0
            for o in self._observations:
                if res > o.resolution:
                    break
                ind += 1
            self._observations.insert(ind, obs)

        self._build_tree()
        self._clear_cache()
629712
def broadcast_1d_array(arr, ndim, axis=1):
    
    ext_arr = arr
    for i in range(ndim - 1):
        ext_arr = np.expand_dims(ext_arr, axis=axis)
    return ext_arr