class_docstr: Class for performing sampling using simple
  Hamiltonian Monte Carlo
  
  Parameters
  ----------
  model: An instance pgmpy.models
      Model from which sampling has to be done
  
  grad_log_pdf: A subclass of pgmpy.inference.continuous.BaseGradLogPDF, defaults to None
      A class to find log and gradient of log distribution for a given assignment
      If None, then will use model.get_gradient_log_pdf
  
  simulate_dynamics: A subclass of pgmpy.inference.continuous.BaseSimulateHamiltonianDynamics
      A class to propose future values of momentum and position in time by simulating
      Hamiltonian Dynamics
  
  Example
  -------
  >>> from pgmpy.sampling import HamiltonianMC as HMC, LeapFrog, GradLogPDFGaussian
  >>> from pgmpy.factors.continuous import GaussianDistribution as JGD
  >>> import numpy as np
  >>> mean = np.array([-3, 4])
  >>> covariance = np.array([[3, 0.7], [0.7, 5]])
  >>> model = JGD(['x', 'y'], mean, covariance)
  >>> sampler = HMC(model=model, grad_log_pdf=GradLogPDFGaussian, simulate_dynamics=LeapFrog)
  >>> samples = sampler.sample(initial_pos=np.array([1, 1]), num_samples = 10000,
  ...                          trajectory_length=2, stepsize=0.4, return_type='recarray')
  >>> samples
  rec.array([(1.0, 1.0), (-3.1861687131079086, 3.7940994520145654),
   (-1.6920542547310844, 6.347410703806017), ...,
   (-1.8093621120575312, 5.940860883943261),
   (0.3933248026088032, 6.3853098838119235),
   (-0.8654072934719572, 6.023803629334816)],
            dtype=[('x', '<f8'), ('y', '<f8')])
  
  >>> samples = np.array([samples[var_name] for var_name in model.variables])
  >>> np.cov(samples)
  array([[ 3.0352818 ,  0.71379304],
         [ 0.71379304,  4.91776713]])
  >>> sampler.accepted_proposals
  9932.0
  >>> sampler.acceptance_rate
  0.9932
  
  References
  ----------
  R.Neal. Handbook of Markov Chain Monte Carlo,
  chapter 5: MCMC Using Hamiltonian Dynamics.
  CRC Press, 2011.
class_docstr_tok: ["Class","for","performing","sampling","using","simple","Hamiltonian","Monte","Carlo","Parameters","--","--","--","--","--","model",":","An","instance","pgmpy.models","Model","from","which","sampling","has","to","be","done","grad_log_pdf",":","A","subclass","of","pgmpy.inference.continuous.BaseGradLogPDF",",","defaults","to","None","A","class","to","find","log","and","gradient","of","log","distribution","for","a","given","assignment","If","None",",","then","will","use","model.get_gradient_log_pdf","simulate_dynamics",":","A","subclass","of","pgmpy.inference.continuous.BaseSimulateHamiltonianDynamics","A","class","to","propose","future","values","of","momentum","and","position","in","time","by","simulating","Hamiltonian","Dynamics","Example","--","--","--","-",">",">",">","from","pgmpy.sampling","import","HamiltonianMC","as","HMC",",","LeapFrog",",","GradLogPDFGaussian",">",">",">","from","pgmpy.factors.continuous","import","GaussianDistribution","as","JGD",">",">",">","import","numpy","as","np",">",">",">","mean","=","np.array","(","[","-3",",","4","]",")",">",">",">","covariance","=","np.array","(","[","[","3",",","0.7","]",",","[","0.7",",","5","]","]",")",">",">",">","model","=","JGD","(","[","'","x","'",",","'","y","'","]",",","mean",",","covariance",")",">",">",">","sampler","=","HMC","(","model=model",",","grad_log_pdf=GradLogPDFGaussian",",","simulate_dynamics=LeapFrog",")",">",">",">","samples","=","sampler.sample","(","initial_pos=np.array","(","[","1",",","1","]",")",",","num_samples","=","10000",",","...","trajectory_length=2",",","stepsize=0.4",",","return_type='recarray","'",")",">",">",">","samples","rec.array","(","[","(","1.0",",","1.0",")",",","(","-3.1861687131079086",",","3.7940994520145654",")",",","(","-1.6920542547310844",",","6.347410703806017",")",",","...",",","(","-1.8093621120575312",",","5.940860883943261",")",",","(","0.3933248026088032",",","6.3853098838119235",")",",","(","-0.8654072934719572",",","6.023803629334816",")","]",",","dtype=","[","(","'","x","'",",","'","<","f8","'",")",",","(","'","y","'",",","'","<","f8","'",")","]",")",">",">",">","samples","=","np.array","(","[","samples","[","var_name","]","for","var_name","in","model.variables","]",")",">",">",">","np.cov","(","samples",")","array","(","[","[","3.0352818",",","0.71379304","]",",","[","0.71379304",",","4.91776713","]","]",")",">",">",">","sampler.accepted_proposals","9932.0",">",">",">","sampler.acceptance_rate","0.9932","References","--","--","--","--","--","R.Neal",".","Handbook","of","Markov","Chain","Monte","Carlo",",","chapter","5",":","MCMC","Using","Hamiltonian","Dynamics",".","CRC","Press",",","2011","."]
docstr: Method to return samples using Hamiltonian Monte Carlo
  
  Parameters
  ----------
  initial_pos: A 1d array like object
      Vector representing values of parameter position, the starting
      state in markov chain.
  
  num_samples: int
      Number of samples to be generated
  
  trajectory_length: int or float
      Target trajectory length, stepsize * number of steps(L),
      where L is the number of steps taken per HMC iteration,
      and stepsize is step size for splitting time method.
  
  stepsize: float , defaults to None
      The stepsize for proposing new values of position and momentum in simulate_dynamics
      If None, then will be chosen suitably
  
  return_type: string (dataframe | recarray)
      Return type for samples, either of 'dataframe' or 'recarray'.
      Defaults to 'dataframe'
  
  Returns
  -------
  sampled: A pandas.DataFrame or a numpy.recarray object depending upon return_type argument
  
  Examples
  --------
  >>> from pgmpy.sampling import HamiltonianMC as HMC, GradLogPDFGaussian, ModifiedEuler
  >>> from pgmpy.factors.continuous import GaussianDistribution as JGD
  >>> import numpy as np
  >>> mean = np.array([1, -1])
  >>> covariance = np.array([[1, 0.2], [0.2, 1]])
  >>> model = JGD(['x', 'y'], mean, covariance)
  >>> sampler = HMC(model=model, grad_log_pdf=GradLogPDFGaussian, simulate_dynamics=ModifiedEuler)
  >>> samples = sampler.sample(np.array([1, 1]), num_samples = 5,
  ...                          trajectory_length=6, stepsize=0.25, return_type='dataframe')
  >>> samples
                 x              y
  0   1.000000e+00   1.000000e+00
  1   1.592133e+00   1.152911e+00
  2   1.608700e+00   1.315349e+00
  3   1.608700e+00   1.315349e+00
  4   6.843856e-01   6.237043e-01
  >>> mean = np.array([4, 1, -1])
  >>> covariance = np.array([[1, 0.7 , 0.8], [0.7, 1, 0.2], [0.8, 0.2, 1]])
  >>> model = JGD(['x', 'y', 'z'], mean, covariance)
  >>> sampler = HMC(model=model, grad_log_pdf=GLPG)
  >>> samples = sampler.sample(np.array([1, 1]), num_samples = 10000,
  ...                          trajectory_length=6, stepsize=0.25, return_type='dataframe')
  >>> np.cov(samples.values.T)
  array([[ 1.00795398,  0.71384233,  0.79802097],
         [ 0.71384233,  1.00633524,  0.21313767],
         [ 0.79802097,  0.21313767,  0.98519017]])
docstr_tok: ["Method","to","return","samples","using","Hamiltonian","Monte","Carlo","Parameters","--","--","--","--","--","initial_pos",":","A","1d","array","like","object","Vector","representing","values","of","parameter","position",",","the","starting","state","in","markov","chain",".","num_samples",":","int","Number","of","samples","to","be","generated","trajectory_length",":","int","or","float","Target","trajectory","length",",","stepsize","*","number","of","steps","(","L",")",",","where","L","is","the","number","of","steps","taken","per","HMC","iteration",",","and","stepsize","is","step","size","for","splitting","time","method",".","stepsize",":","float",",","defaults","to","None","The","stepsize","for","proposing","new","values","of","position","and","momentum","in","simulate_dynamics","If","None",",","then","will","be","chosen","suitably","return_type",":","string","(","dataframe","|","recarray",")","Return","type","for","samples",",","either","of","'dataframe","'","or","'recarray","'",".","Defaults","to","'dataframe'","Returns","--","--","--","-","sampled",":","A","pandas.DataFrame","or","a","numpy.recarray","object","depending","upon","return_type","argument","Examples","--","--","--","--",">",">",">","from","pgmpy.sampling","import","HamiltonianMC","as","HMC",",","GradLogPDFGaussian",",","ModifiedEuler",">",">",">","from","pgmpy.factors.continuous","import","GaussianDistribution","as","JGD",">",">",">","import","numpy","as","np",">",">",">","mean","=","np.array","(","[","1",",","-1","]",")",">",">",">","covariance","=","np.array","(","[","[","1",",","0.2","]",",","[","0.2",",","1","]","]",")",">",">",">","model","=","JGD","(","[","'","x","'",",","'","y","'","]",",","mean",",","covariance",")",">",">",">","sampler","=","HMC","(","model=model",",","grad_log_pdf=GradLogPDFGaussian",",","simulate_dynamics=ModifiedEuler",")",">",">",">","samples","=","sampler.sample","(","np.array","(","[","1",",","1","]",")",",","num_samples","=","5",",","...","trajectory_length=6",",","stepsize=0.25",",","return_type='dataframe","'",")",">",">",">","samples","x","y","0","1.000000e+00","1.000000e+00","1","1.592133e+00","1.152911e+00","2","1.608700e+00","1.315349e+00","3","1.608700e+00","1.315349e+00","4","6.843856e-01","6.237043e-01",">",">",">","mean","=","np.array","(","[","4",",","1",",","-1","]",")",">",">",">","covariance","=","np.array","(","[","[","1",",","0.7",",","0.8","]",",","[","0.7",",","1",",","0.2","]",",","[","0.8",",","0.2",",","1","]","]",")",">",">",">","model","=","JGD","(","[","'","x","'",",","'","y","'",",","'","z","'","]",",","mean",",","covariance",")",">",">",">","sampler","=","HMC","(","model=model",",","grad_log_pdf=GLPG",")",">",">",">","samples","=","sampler.sample","(","np.array","(","[","1",",","1","]",")",",","num_samples","=","10000",",","...","trajectory_length=6",",","stepsize=0.25",",","return_type='dataframe","'",")",">",">",">","np.cov","(","samples.values.T",")","array","(","[","[","1.00795398",",","0.71384233",",","0.79802097","]",",","[","0.71384233",",","1.00633524",",","0.21313767","]",",","[","0.79802097",",","0.21313767",",","0.98519017","]","]",")"]
code: def sample(
      self,
      initial_pos,
      num_samples,
      trajectory_length,
      stepsize=None,
      return_type="dataframe",
  ):
      """
      Method to return samples using Hamiltonian Monte Carlo
  
      Parameters
      ----------
      initial_pos: A 1d array like object
          Vector representing values of parameter position, the starting
          state in markov chain.
  
      num_samples: int
          Number of samples to be generated
  
      trajectory_length: int or float
          Target trajectory length, stepsize * number of steps(L),
          where L is the number of steps taken per HMC iteration,
          and stepsize is step size for splitting time method.
  
      stepsize: float , defaults to None
          The stepsize for proposing new values of position and momentum in simulate_dynamics
          If None, then will be chosen suitably
  
      return_type: string (dataframe | recarray)
          Return type for samples, either of 'dataframe' or 'recarray'.
          Defaults to 'dataframe'
  
      Returns
      -------
      sampled: A pandas.DataFrame or a numpy.recarray object depending upon return_type argument
  
      Examples
      --------
      >>> from pgmpy.sampling import HamiltonianMC as HMC, GradLogPDFGaussian, ModifiedEuler
      >>> from pgmpy.factors.continuous import GaussianDistribution as JGD
      >>> import numpy as np
      >>> mean = np.array([1, -1])
      >>> covariance = np.array([[1, 0.2], [0.2, 1]])
      >>> model = JGD(['x', 'y'], mean, covariance)
      >>> sampler = HMC(model=model, grad_log_pdf=GradLogPDFGaussian, simulate_dynamics=ModifiedEuler)
      >>> samples = sampler.sample(np.array([1, 1]), num_samples = 5,
      ...                          trajectory_length=6, stepsize=0.25, return_type='dataframe')
      >>> samples
                     x              y
      0   1.000000e+00   1.000000e+00
      1   1.592133e+00   1.152911e+00
      2   1.608700e+00   1.315349e+00
      3   1.608700e+00   1.315349e+00
      4   6.843856e-01   6.237043e-01
      >>> mean = np.array([4, 1, -1])
      >>> covariance = np.array([[1, 0.7 , 0.8], [0.7, 1, 0.2], [0.8, 0.2, 1]])
      >>> model = JGD(['x', 'y', 'z'], mean, covariance)
      >>> sampler = HMC(model=model, grad_log_pdf=GLPG)
      >>> samples = sampler.sample(np.array([1, 1]), num_samples = 10000,
      ...                          trajectory_length=6, stepsize=0.25, return_type='dataframe')
      >>> np.cov(samples.values.T)
      array([[ 1.00795398,  0.71384233,  0.79802097],
             [ 0.71384233,  1.00633524,  0.21313767],
             [ 0.79802097,  0.21313767,  0.98519017]])
      """
  
      self.accepted_proposals = 1.0
      initial_pos = _check_1d_array_object(initial_pos, "initial_pos")
      _check_length_equal(
          initial_pos,
          self.model.variables,
          "initial_pos",
          "model.variables",
      )
  
      if stepsize is None:
          stepsize = self._find_reasonable_stepsize(initial_pos)
  
      types = [(var_name, "float") for var_name in self.model.variables]
      samples = np.zeros(num_samples, dtype=types).view(np.recarray)
  
      # Assigning after converting into tuple because value was being changed after assignment
      # Reason for this is unknown
      samples[0] = tuple(initial_pos)
      position_m = initial_pos
  
      lsteps = int(max(1, round(trajectory_length / stepsize, 0)))
      for i in tqdm(range(1, num_samples)):
          # Generating sample
          position_m, _ = self._sample(
              position_m, trajectory_length, stepsize, lsteps
          )
          samples[i] = tuple(position_m)
  
      self.acceptance_rate = self.accepted_proposals / num_samples
  
      return _return_samples(samples)
  
file_path: pgmpy/pgmpy/sampling/HMC.py
imports: from math import sqrt
  import numpy
  from tqdm.auto import tqdm
  from pgmpy.sampling import BaseGradLogPDF, BaseSimulateHamiltonianDynamics, LeapFrog, _return_samples
  from pgmpy.utils import _check_1d_array_object, _check_length_equal
label_desc: Use image node_id 6 for calling the HamiltonianMC obj's underlying member method code with example usage: obj.sample(initial_pos, num_samples, trajectory_length, stepsize, return_type) and returns: _return_samples