jVMC 1.2.4__tar.gz → 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. {jVMC-1.2.4 → jvmc-1.3.0}/PKG-INFO +31 -2
  2. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/rnn1d_general.py +2 -2
  3. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/rnn2d_general.py +1 -1
  4. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/operator/base.py +31 -0
  5. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/operator/branch_free.py +100 -7
  6. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/stats.py +127 -16
  7. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/tdvp.py +25 -17
  8. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/version.py +1 -1
  9. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/vqs.py +0 -1
  10. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC.egg-info/PKG-INFO +31 -2
  11. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC.egg-info/requires.txt +8 -4
  12. {jVMC-1.2.4 → jvmc-1.3.0}/setup.py +1 -2
  13. {jVMC-1.2.4 → jvmc-1.3.0}/tests/nets_test.py +30 -5
  14. {jVMC-1.2.4 → jvmc-1.3.0}/tests/operator_test.py +38 -0
  15. {jVMC-1.2.4 → jvmc-1.3.0}/tests/povm_test.py +1 -1
  16. jvmc-1.3.0/tests/stats_test.py +111 -0
  17. {jVMC-1.2.4 → jvmc-1.3.0}/tests/tdvp_test.py +2 -2
  18. jVMC-1.2.4/tests/stats_test.py +0 -35
  19. {jVMC-1.2.4 → jvmc-1.3.0}/LICENSE +0 -0
  20. {jVMC-1.2.4 → jvmc-1.3.0}/README.md +0 -0
  21. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/__init__.py +0 -0
  22. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/global_defs.py +0 -0
  23. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/mpi_wrapper.py +0 -0
  24. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/__init__.py +0 -0
  25. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/activation_functions.py +0 -0
  26. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/cnn.py +0 -0
  27. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/ffn.py +0 -0
  28. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/initializers.py +0 -0
  29. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/rbm.py +0 -0
  30. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/sym_wrapper.py +0 -0
  31. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/nets/two_nets_wrapper.py +0 -0
  32. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/operator/__init__.py +0 -0
  33. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/operator/povm.py +0 -0
  34. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/sampler.py +0 -0
  35. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/__init__.py +0 -0
  36. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/minsr.py +0 -0
  37. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/output_manager.py +0 -0
  38. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/stepper.py +0 -0
  39. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/symmetries.py +0 -0
  40. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC/util/util.py +0 -0
  41. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC.egg-info/SOURCES.txt +0 -0
  42. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC.egg-info/dependency_links.txt +0 -0
  43. {jVMC-1.2.4 → jvmc-1.3.0}/jVMC.egg-info/top_level.txt +0 -0
  44. {jVMC-1.2.4 → jvmc-1.3.0}/setup.cfg +0 -0
  45. {jVMC-1.2.4 → jvmc-1.3.0}/tests/__init__.py +0 -0
  46. {jVMC-1.2.4 → jvmc-1.3.0}/tests/minsr_test.py +0 -0
  47. {jVMC-1.2.4 → jvmc-1.3.0}/tests/mpi_wrapper_test.py +0 -0
  48. {jVMC-1.2.4 → jvmc-1.3.0}/tests/sampler_test.py +0 -0
  49. {jVMC-1.2.4 → jvmc-1.3.0}/tests/stepper_test.py +0 -0
  50. {jVMC-1.2.4 → jvmc-1.3.0}/tests/symmetries_test.py +0 -0
  51. {jVMC-1.2.4 → jvmc-1.3.0}/tests/vqs_test.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: jVMC
3
- Version: 1.2.4
3
+ Version: 1.3.0
4
4
  Summary: jVMC: Versatile and performant variational Monte Carlo
5
5
  Home-page: https://jvmc.readthedocs.io/en/latest/#
6
6
  Author: Markus Schmitt, Moritz Reh
@@ -9,8 +9,37 @@ Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
11
  Description-Content-Type: text/markdown
12
- Provides-Extra: dev
13
12
  License-File: LICENSE
13
+ Requires-Dist: setuptools
14
+ Requires-Dist: wheel
15
+ Requires-Dist: numpy
16
+ Requires-Dist: openfermion
17
+ Requires-Dist: jax<=0.4.20,>=0.4.1
18
+ Requires-Dist: jaxlib<=0.4.20,>=0.4.1
19
+ Requires-Dist: flax<=0.6.11,>=0.6.4
20
+ Requires-Dist: mpi4py
21
+ Requires-Dist: h5py
22
+ Requires-Dist: PyYAML
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: scipy<1.13
25
+ Provides-Extra: dev
26
+ Requires-Dist: setuptools; extra == "dev"
27
+ Requires-Dist: wheel; extra == "dev"
28
+ Requires-Dist: numpy; extra == "dev"
29
+ Requires-Dist: openfermion; extra == "dev"
30
+ Requires-Dist: jax<=0.4.20,>=0.4.1; extra == "dev"
31
+ Requires-Dist: jaxlib<=0.4.20,>=0.4.1; extra == "dev"
32
+ Requires-Dist: flax<=0.6.11,>=0.6.4; extra == "dev"
33
+ Requires-Dist: mpi4py; extra == "dev"
34
+ Requires-Dist: h5py; extra == "dev"
35
+ Requires-Dist: PyYAML; extra == "dev"
36
+ Requires-Dist: matplotlib; extra == "dev"
37
+ Requires-Dist: scipy<1.13; extra == "dev"
38
+ Requires-Dist: sphinx; extra == "dev"
39
+ Requires-Dist: mock; extra == "dev"
40
+ Requires-Dist: sphinx_rtd_theme; extra == "dev"
41
+ Requires-Dist: pytest; extra == "dev"
42
+ Requires-Dist: pytest-mpi; extra == "dev"
14
43
 
15
44
  [![Documentation Status](https://readthedocs.org/projects/jvmc/badge/?version=latest)](https://jvmc.readthedocs.io/en/latest/?badge=latest)
16
45
  [![PyPi version](https://badgen.net/pypi/v/jVMC/)](https://pypi.org/project/jVMC/)
@@ -112,7 +112,7 @@ class RNN1DGeneral(nn.Module):
112
112
  self.initFunction = jax.nn.initializers.variance_scaling(scale=self.initScale, mode="fan_avg", distribution="uniform")
113
113
  else:
114
114
  self.dtype = global_defs.tCpx
115
- self.initFunction = partial(jVMC.nets.initializers.cplx_variance_scaling, scale=self.initScale)
115
+ self.initFunction = jVMC.nets.initializers.cplx_variance_scaling
116
116
 
117
117
  if isinstance(self.cell, str):
118
118
  self.zero_carry = jnp.zeros((self.depth, 1, self.hiddenSize), dtype=self.dtype)
@@ -129,7 +129,7 @@ class RNN1DGeneral(nn.Module):
129
129
  self.cells = self.cell[0]
130
130
  self.zero_carry = self.cell[1]
131
131
 
132
- self.rnnCell = RNNCellStack(self.cells, actFun=self.actFun)
132
+ self.rnnCell = RNNCellStack(self.cells, actFun=self.actFun, dtype=self.dtype)
133
133
  init_args = init_fn_args(dtype=self.dtype, bias_init=jax.nn.initializers.zeros, kernel_init=self.initFunction)
134
134
  self.outputDense = nn.Dense(features=(self.inputDim-1) * (2 - self.realValuedOutput),
135
135
  use_bias=True, **init_args)
@@ -117,7 +117,7 @@ class RNN2DGeneral(nn.Module):
117
117
  self.initFunction = jax.nn.initializers.variance_scaling(scale=self.initScale, mode="fan_avg", distribution="uniform")
118
118
  else:
119
119
  self.dtype = global_defs.tCpx
120
- self.initFunction = partial(jVMC.nets.initializers.cplx_variance_scaling, scale=self.initScale)
120
+ self.initFunction = jVMC.nets.initializers.cplx_variance_scaling
121
121
 
122
122
  if isinstance(self.cell, str):
123
123
  if self.cell in ["LSTM", "GRU"] and not self.realValuedParams:
@@ -279,3 +279,34 @@ class Operator(metaclass=abc.ABCMeta):
279
279
  corresponding matrix elements.
280
280
  """
281
281
 
282
+ def get_estimator_function(self, psi, *args):
283
+ """Get a function that computes :math:`O_{loc}(\\theta, s)`.
284
+
285
+ Returns a function that computes :math:`O_{loc}(\\theta, s)=\sum_{s'} O_{s,s'}\\frac{\psi_\\theta(s')}{\psi_\\theta(s)}`
286
+ for a given configuration :math:`s` and parameters :math:`\\theta` of a given ansatz :math:`\psi_\\theta(s)`.
287
+
288
+ Arguments:
289
+ * ``psi``: Neural quantum state.
290
+ * ``*args``: Further positional arguments for the operator.
291
+
292
+ Returns:
293
+ A function :math:`O_{loc}(\\theta, s)`.
294
+ """
295
+
296
+ op_fun = self.compile()
297
+ if type(op_fun) is tuple:
298
+ op_fun_args = op_fun[1](*args)
299
+ op_fun = op_fun[0]
300
+ net_fun = psi.net.apply
301
+
302
+ def op_estimator(params, config):
303
+
304
+ sp, matEls = op_fun(config, *op_fun_args)
305
+
306
+ log_psi_s = net_fun(params, config)
307
+ log_psi_sp = jax.vmap(lambda s: net_fun(params,s))(sp)
308
+
309
+ #return jnp.dot(matEls, jnp.exp(log_psi_sp - log_psi_s))
310
+ return jnp.sum(matEls * jnp.exp(log_psi_sp - log_psi_s))
311
+
312
+ return op_estimator
@@ -107,6 +107,73 @@ def Sm(idx):
107
107
  return {'idx': idx, 'map': jnp.array([0, 0], dtype=np.int32), 'matEls': jnp.array([0.0, 1.0], dtype=opDtype), 'diag': False}
108
108
 
109
109
 
110
+ ######################
111
+ # fermionic number operator
112
+ def number(idx):
113
+ """Returns a :math:`c^\dagger c` femrioic number operator
114
+
115
+ Args:
116
+
117
+ * ``idx``: Index of the local Hilbert space.
118
+
119
+ Returns:
120
+ Dictionary defining :math:`c^\dagger c` femrioic number operator
121
+
122
+ """
123
+
124
+ return {
125
+ 'idx': idx,
126
+ 'map': jax.numpy.array([0,1],dtype=np.int32),
127
+ 'matEls': jax.numpy.array([0.,1.],dtype=opDtype),
128
+ 'diag': True,
129
+ 'fermionic': False
130
+ }
131
+
132
+ ######################
133
+ # fermionic creation operator
134
+ def creation(idx):
135
+ """Returns a :math:`c^\dagger` femrioic creation operator
136
+
137
+ Args:
138
+
139
+ * ``idx``: Index of the local Hilbert space.
140
+
141
+ Returns:
142
+ Dictionary defining :math:`c^\dagger` femrioic creation operator
143
+
144
+ """
145
+
146
+ return {
147
+ 'idx': idx,
148
+ 'map': jax.numpy.array([1,0],dtype=np.int32),
149
+ 'matEls': jax.numpy.array([1.,0.],dtype=opDtype),
150
+ 'diag': False,
151
+ "fermionic": True
152
+ }
153
+
154
+ ######################
155
+ # fermionic annihilation operator
156
+ def annihilation(idx):
157
+ """Returns a :math:`c` femrioic creation operator
158
+
159
+ Args:
160
+
161
+ * ``idx``: Index of the local Hilbert space.
162
+
163
+ Returns:
164
+ Dictionary defining :math:`c` femrioic creation operator
165
+
166
+ """
167
+
168
+ return {
169
+ 'idx': idx,
170
+ 'map': jax.numpy.array([1,0],dtype=np.int32),
171
+ 'matEls': jax.numpy.array([0.,1.],dtype=opDtype),
172
+ 'diag': False,
173
+ "fermionic": True
174
+ }
175
+
176
+
110
177
  import copy
111
178
 
112
179
  @jax.jit
@@ -179,6 +246,9 @@ class BranchFreeOperator(Operator):
179
246
  self.matEls = []
180
247
  self.diag = []
181
248
  self.prefactor = []
249
+ ######## fermions ########
250
+ self.fermionic = []
251
+ ##########################
182
252
  self.maxOpStrLength = 0
183
253
  for op in self.ops:
184
254
  tmpLen = len(op)
@@ -192,6 +262,7 @@ class BranchFreeOperator(Operator):
192
262
  self.idx.append([])
193
263
  self.map.append([])
194
264
  self.matEls.append([])
265
+ self.fermionic.append([])
195
266
  # check whether string contains prefactor
196
267
  k0=0
197
268
  if callable(op[0]):
@@ -207,10 +278,20 @@ class BranchFreeOperator(Operator):
207
278
  self.idx[o].append(op[k]['idx'])
208
279
  self.map[o].append(op[k]['map'])
209
280
  self.matEls[o].append(op[k]['matEls'])
281
+ ######## fermions ########
282
+ fermi_check = True
283
+ if "fermionic" in op[k]:
284
+ if op[k]["fermionic"]:
285
+ fermi_check = False
286
+ self.fermionic[o].append(1.)
287
+ if fermi_check:
288
+ self.fermionic[o].append(0.)
289
+ ##########################
210
290
  else:
211
291
  self.idx[o].append(IdOp['idx'])
212
292
  self.map[o].append(IdOp['map'])
213
293
  self.matEls[o].append(IdOp['matEls'])
294
+ self.fermionic[o].append(0.)
214
295
 
215
296
  if isDiagonal:
216
297
  self.diag.append(o)
@@ -219,6 +300,9 @@ class BranchFreeOperator(Operator):
219
300
  self.idxC = jnp.array(self.idx, dtype=np.int32)
220
301
  self.mapC = jnp.array(self.map, dtype=np.int32)
221
302
  self.matElsC = jnp.array(self.matEls, dtype=opDtype)
303
+ ######## fermions ########
304
+ self.fermionicC = jnp.array(self.fermionic, dtype=np.int32)
305
+ ##########################
222
306
  self.diag = jnp.array(self.diag, dtype=np.int32)
223
307
 
224
308
  def arg_fun(*args, prefactor, init):
@@ -243,10 +327,10 @@ class BranchFreeOperator(Operator):
243
327
 
244
328
  return (jnp.array(res), )
245
329
 
246
- return functools.partial(self._get_s_primes, idxC=self.idxC, mapC=self.mapC, matElsC=self.matElsC, diag=self.diag, prefactor=self.prefactor),\
330
+ return functools.partial(self._get_s_primes, idxC=self.idxC, mapC=self.mapC, matElsC=self.matElsC, diag=self.diag, fermiC=self.fermionicC, prefactor=self.prefactor),\
247
331
  functools.partial(arg_fun, prefactor=self.prefactor, init=np.ones(self.idxC.shape[0], dtype=self.matElsC.dtype))
248
332
 
249
- def _get_s_primes(self, s, *args, idxC, mapC, matElsC, diag, prefactor):
333
+ def _get_s_primes(self, s, *args, idxC, mapC, matElsC, diag, fermiC, prefactor):
250
334
 
251
335
  numOps = idxC.shape[0]
252
336
  #matEl = jnp.ones(numOps, dtype=matElsC.dtype)
@@ -254,28 +338,37 @@ class BranchFreeOperator(Operator):
254
338
 
255
339
  sp = jnp.array([s] * numOps)
256
340
 
341
+ ######## fermions ########
342
+ mask = jnp.tril(jnp.ones((s.shape[-1],s.shape[-1]),dtype=int),-1).T
343
+ ##########################
344
+
257
345
  def apply_fun(c, x):
258
346
  config, configMatEl = c
259
- idx, sMap, matEls = x
347
+ idx, sMap, matEls, fermi = x
260
348
 
261
349
  configShape = config.shape
262
350
  config = config.ravel()
263
- configMatEl = configMatEl * matEls[config[idx]]
351
+ ######## fermions ########
352
+ configMatEl = configMatEl * matEls[config[idx]] * jnp.prod((1 - 2 * fermi) * \
353
+ (2 * fermi * mask[idx] +\
354
+ (1 - 2 * fermi)) * config + \
355
+ (1 - abs(config)))
356
+ ##########################
264
357
  config = config.at[idx].set(sMap[config[idx]])
265
358
 
266
359
  return (config.reshape(configShape), configMatEl), None
267
360
 
268
361
  #def apply_multi(config, configMatEl, opIdx, opMap, opMatEls, prefactor):
269
- def apply_multi(config, configMatEl, opIdx, opMap, opMatEls):
362
+ def apply_multi(config, configMatEl, opIdx, opMap, opMatEls, opFermi):
270
363
 
271
- (config, configMatEl), _ = jax.lax.scan(apply_fun, (config, configMatEl), (opIdx, opMap, opMatEls))
364
+ (config, configMatEl), _ = jax.lax.scan(apply_fun, (config, configMatEl), (opIdx, opMap, opMatEls, opFermi))
272
365
 
273
366
  #return config, prefactor*configMatEl
274
367
  return config, configMatEl
275
368
 
276
369
  # vmap over operators
277
370
  #sp, matEl = vmap(apply_multi, in_axes=(0, 0, 0, 0, 0, 0))(sp, matEl, idxC, mapC, matElsC, jnp.array([f(*args) for f in prefactor]))
278
- sp, matEl = vmap(apply_multi, in_axes=(0, 0, 0, 0, 0))(sp, matEl, idxC, mapC, matElsC)
371
+ sp, matEl = vmap(apply_multi, in_axes=(0, 0, 0, 0, 0, 0))(sp, matEl, idxC, mapC, matElsC, fermiC)
279
372
  if len(diag) > 1:
280
373
  matEl = matEl.at[diag[0]].set(jnp.sum(matEl[diag], axis=0))
281
374
  matEl = matEl.at[diag[1:]].set(jnp.zeros((diag.shape[0] - 1,), dtype=matElsC.dtype))
@@ -1,11 +1,16 @@
1
1
  import jax
2
2
  import jax.numpy as jnp
3
+ from jax.tree_util import tree_flatten, tree_unflatten, tree_map
3
4
 
4
5
  import jVMC
5
6
  import jVMC.mpi_wrapper as mpi
6
7
  import jVMC.global_defs as global_defs
7
8
  from jVMC.global_defs import pmap_for_my_devices
8
9
 
10
+ import numpy as np
11
+
12
+ from functools import partial
13
+
9
14
  _mean_helper = None
10
15
  _data_prep = None
11
16
  _covar_helper = None
@@ -82,46 +87,151 @@ def jit_my_stuff():
82
87
  _subset_data_prep = jVMC.global_defs.pmap_for_my_devices(jax.vmap(lambda d, w, m1, m2: d+jnp.sqrt(w)*(m1-m2), in_axes=(0,0,None,None)), in_axes=(0,0,None,None))
83
88
 
84
89
 
90
+ # def get_op_estimator(psi, operator, *args):
91
+
92
+ # op_fun = operator.compile()
93
+ # if type(op_fun) is tuple:
94
+ # op_fun_args = op_fun[1](*args)
95
+ # op_fun = op_fun[0]
96
+ # net_fun = psi.net.apply
97
+
98
+ # def op_estimator(params, config):
99
+
100
+ # sp, matEls = op_fun(config, *op_fun_args)
101
+
102
+ # log_psi_s = net_fun(params, config)
103
+ # log_psi_sp = jax.vmap(lambda s: net_fun(params,s))(sp)
104
+
105
+ # return jnp.dot(matEls, jnp.exp(log_psi_sp - log_psi_s))
106
+
107
+ # return op_estimator
108
+
109
+
110
+ def flat_grad(fun):
111
+
112
+ def grad_fun(*args):
113
+ grad_tree = jax.grad(fun)(*args)
114
+
115
+ dtypes = [a.dtype for a in tree_flatten(args[0])[0]]
116
+ if dtypes[0] == np.single or dtypes[0] == np.double:
117
+ grad_vec = tree_flatten(
118
+ tree_map(
119
+ lambda x: x.ravel(),
120
+ grad_tree
121
+ )
122
+ )[0]
123
+ else:
124
+ grad_vec = tree_flatten(
125
+ tree_map(
126
+ lambda x: [jnp.real(x.ravel()), -jnp.imag(x.ravel())],
127
+ grad_tree
128
+ )
129
+ )[0]
130
+
131
+ return jnp.concatenate(grad_vec)
132
+
133
+ return grad_fun
134
+
135
+
85
136
  class SampledObs():
86
137
  """This class implements the computation of statistics from Monte Carlo or exact samples.
87
138
 
88
139
  Initializer arguments:
89
- * ``observations``: Observations :math:`O_n` in the sample. The array must have a leading device \
90
- dimension plus a batch dimension.
140
+ * ``observations``: Observations :math:`O_n` in the sample. This can be the value of an observable `O(s_n)` or the \
141
+ plain configuration `s_n`. The array must have a leading device dimension plus a batch dimension.
91
142
  * ``weights``: Weights :math:`w_n` associated with observation :math:`O_n`.
143
+ * ``estimator``: [optional] Function :math:`O(\\theta, s)` that computes an estimator parametrized by :math:`\\theta`
144
+ * ``params``: [optional] A set of parameters for the estimator function.
92
145
  """
93
146
 
94
- def __init__(self, observations=None, weights=None):
147
+ def __init__(
148
+ self,
149
+ observations=None,
150
+ weights=None,
151
+ estimator=None,
152
+ params=None
153
+ ):
95
154
  """Initializes SampledObs class.
96
155
 
97
156
  Args:
98
- * ``observations``: Observations :math:`O_n` in the sample. The array must have a leading device \
99
- dimension plus a batch dimension.
157
+ * ``observations``: Observations :math:`O_n` in the sample. This can be the value of an observable `O(s_n)` or the \
158
+ plain configuration `s_n`. The array must have a leading device dimension plus a batch dimension.
100
159
  * ``weights``: Weights :math:`w_n` associated with observation :math:`O_n`.
160
+ * ``estimator``: [optional] Function :math:`O(\\theta, s)` that computes an estimator parametrized by :math:`\\theta`
161
+ * ``params``: [optional] A set of parameters for the estimator function.
101
162
  """
102
163
 
103
164
  jit_my_stuff()
104
165
 
105
- if (observations is not None) and (weights is not None):
166
+ self._weights = weights
167
+ self._data = observations
168
+ self._mean = None
169
+ self._configs = None
170
+ def estimator_not_implemented(p,s):
171
+ raise Exception("No estimator function given.")
172
+
173
+ self._estimator = estimator_not_implemented
174
+ self._estimator_grad = estimator_not_implemented
175
+
176
+ if estimator is not None:
177
+
178
+ self._configs = observations
179
+
180
+ self._estimator = jVMC.global_defs.pmap_for_my_devices(
181
+ jax.vmap(lambda p, s: estimator(p,s), in_axes=(None, 0)),
182
+ in_axes=(None, 0)
183
+ )
184
+
185
+ self._estimator_grad = jVMC.global_defs.pmap_for_my_devices(
186
+ jax.vmap(lambda p, s: flat_grad(lambda a, b: jnp.real(estimator(a,b)))(p,s) + 1.j*flat_grad(lambda a, b: jnp.imag(estimator(a,b)))(p,s), in_axes=(None, 0)),
187
+ in_axes=(None, 0)
188
+ )
189
+
190
+ if params is not None:
191
+
192
+ observations = self._estimator(params, self._configs)
193
+
194
+ self._compute_data_and_mean(observations)
195
+
196
+
197
+ def _compute_data_and_mean(self, observations):
198
+
199
+ if (observations is not None) and (self._weights is not None):
106
200
  if len(observations.shape) == 2:
107
201
  observations = observations[...,None]
108
202
 
109
- self._weights = weights
110
- self._mean = mpi.global_sum( _mean_helper(observations,self._weights)[None,...] )
203
+ #self._weights = weights
204
+ self._mean = mpi.global_sum( _mean_helper(observations,self._weights)[:, None,...] )
111
205
  self._data = _data_prep(observations, self._weights, self._mean)
112
- else:
113
- self._weights = weights
114
- self._data = observations
115
- self._mean = None
116
206
 
117
207
 
118
- def mean(self):
208
+ def mean(self, params=None):
119
209
  """Returns the mean.
120
210
  """
121
211
 
212
+ if params is not None:
213
+ observations = self._estimator(params, self._configs)
214
+ self._compute_data_and_mean(observations)
215
+
122
216
  return self._mean
123
217
 
124
218
 
219
+ def mean_and_grad(self, psi, params):
220
+ """Returns the mean and gradient of the given estimator.
221
+ """
222
+
223
+ obs = self._estimator(params, self._configs)
224
+ self._compute_data_and_mean(obs)
225
+
226
+ obsGrad = self._estimator_grad(params, self._configs)
227
+ obsGradMean = mpi.global_sum( _mean_helper(obsGrad,self._weights)[None,...] )
228
+
229
+ psiGrad = SampledObs( 2.0*jnp.real( psi.gradients(self._configs) ), self._weights )
230
+
231
+ return self._mean, psiGrad.covar(self).ravel() + obsGradMean
232
+
233
+
234
+
125
235
  def covar(self, other=None):
126
236
  """Returns the covariance.
127
237
 
@@ -132,7 +242,7 @@ class SampledObs():
132
242
  if other is None:
133
243
  other = self
134
244
 
135
- return mpi.global_sum( _covar_helper(self._data, other._data)[None,...] )
245
+ return mpi.global_sum( _covar_helper(self._data, other._data)[:, None,...] )
136
246
 
137
247
 
138
248
  def var(self):
@@ -165,7 +275,7 @@ class SampledObs():
165
275
  if other is None:
166
276
  other = self
167
277
 
168
- return mpi.global_sum( _covar_var_helper(self._data, other._data, self._weights)[None,...] ) \
278
+ return mpi.global_sum( _covar_var_helper(self._data, other._data, self._weights)[:, None,...] ) \
169
279
  - jnp.abs(self.covar(other))**2
170
280
 
171
281
 
@@ -212,7 +322,8 @@ class SampledObs():
212
322
  newObs._data = _get_subset_helper(self._data, (start, end, step))
213
323
  newObs._weights = newObs._weights / normalization
214
324
  newObs._data = newObs._data / jnp.sqrt(normalization)
215
- newObs._mean = mpi.global_sum( _subset_mean_helper(newObs._data, newObs._weights, self._mean)[None,...] )
325
+
326
+ newObs._mean = mpi.global_sum( _subset_mean_helper(newObs._data, newObs._weights, 0.0)[:,None,...] ) + self._mean
216
327
  newObs._data = _subset_data_prep(newObs._data, newObs._weights, self._mean, newObs._mean)
217
328
 
218
329
  return newObs
@@ -36,7 +36,7 @@ class TDVP:
36
36
 
37
37
  and for real parameters :math:`\\theta\in\mathbb R`, the TDVP equation reads
38
38
 
39
- :math:`q\\big[S_{k,k'}\\big]\\theta_{k'} = -q\\big[xF_k\\big]`
39
+ :math:`q\\big[S_{k,k'}\\big]\\dot\\theta_{k'} = -q\\big[xF_k\\big]`
40
40
 
41
41
  Here, either :math:`q=\\text{Re}` or :math:`q=\\text{Im}` and :math:`x=1` for ground state
42
42
  search or :math:`x=i` (the imaginary unit) for real time dynamics.
@@ -62,7 +62,8 @@ class TDVP:
62
62
  Initializer arguments:
63
63
  * ``sampler``: A sampler object.
64
64
  * ``snrTol``: Regularization parameter :math:`\epsilon_{SNR}`, see above.
65
- * ``pinvTol``: Regularization parameter :math:`\epsilon_{SVD}`, see above.
65
+ * ``pinvTol``: Regularization parameter :math:`\epsilon_{SVD}` (see above) is chosen such that :math:`||S\\dot\\theta-F|| / ||F||<pinvTol`.
66
+ * ``pinvCutoff``: Lower bound for the regularization parameter :math:`\epsilon_{SVD}`, see above.
66
67
  * ``makeReal``: Specifies the function :math:`q`, either `'real'` for :math:`q=\\text{Re}` or `'imag'` for :math:`q=\\text{Im}`.
67
68
  * ``rhsPrefactor``: Prefactor :math:`x` of the right hand side, see above.
68
69
  * ``diagonalShift``: Regularization parameter :math:`\\rho` for ground state search, see above.
@@ -70,15 +71,12 @@ class TDVP:
70
71
  * ``diagonalizeOnDevice``: Choose whether to diagonalize :math:`S` on GPU or CPU.
71
72
  """
72
73
 
73
- def __init__(self, sampler, snrTol=2, pinvTol=1e-14, svdTol=None, makeReal='imag', rhsPrefactor=1.j, diagonalShift=0., crossValidation=False, diagonalizeOnDevice=True):
74
+ def __init__(self, sampler, snrTol=2, pinvTol=1e-14, pinvCutoff=1e-8, makeReal='imag', rhsPrefactor=1.j, diagonalShift=0., crossValidation=False, diagonalizeOnDevice=True):
74
75
 
75
- if svdTol is not None:
76
- warnings.warn("Parameter `svdTol` is deprecated. Use `pinvTol` instead.", DeprecationWarning)
77
- pinvTol = svdTol
78
-
79
76
  self.sampler = sampler
80
77
  self.snrTol = snrTol
81
78
  self.pinvTol = pinvTol
79
+ self.pinvCutoff = pinvCutoff
82
80
  self.diagonalShift = diagonalShift
83
81
  self.rhsPrefactor = rhsPrefactor
84
82
  self.crossValidation = crossValidation
@@ -194,16 +192,25 @@ class TDVP:
194
192
  # Discard eigenvalues below numerical precision
195
193
  self.invEv = jnp.where(jnp.abs(self.ev / self.ev[-1]) > 1e-14, 1. / self.ev, 0.)
196
194
 
197
- # Set regularizer for singular value cutoff
198
- regularizer = 1. / (1. + (self.pinvTol / jnp.abs(self.ev / self.ev[-1]))**6)
195
+ residual = 1.0
196
+ cutoff = 1e-2
197
+ F_norm = jnp.linalg.norm(F)
198
+ while residual > self.pinvTol and cutoff > self.pinvCutoff:
199
+ cutoff *= 0.8
200
+ # Set regularizer for singular value cutoff
201
+ regularizer = 1. / (1. + (max(cutoff, self.pinvCutoff) / jnp.abs(self.ev / self.ev[-1]))**6)
199
202
 
200
- if not isinstance(self.sampler, jVMC.sampler.ExactSampler):
201
- # Construct a soft cutoff based on the SNR
202
- regularizer *= 1. / (1. + (self.snrTol / self.snr)**6)
203
+ if not isinstance(self.sampler, jVMC.sampler.ExactSampler):
204
+ # Construct a soft cutoff based on the SNR
205
+ regularizer *= 1. / (1. + (self.snrTol / self.snr)**6)
203
206
 
204
- update = jnp.real(jnp.dot(self.V, (self.invEv * regularizer * self.VtF)))
207
+ pinvEv = self.invEv * regularizer
205
208
 
206
- return update, jnp.linalg.norm(self.S.dot(update) - F) / jnp.linalg.norm(F)
209
+ residual = jnp.linalg.norm((pinvEv * self.ev - jnp.ones_like(pinvEv)) * self.VtF) / F_norm
210
+
211
+ update = jnp.real(jnp.dot(self.V, (pinvEv * self.VtF)))
212
+
213
+ return update, residual, max(cutoff, self.pinvCutoff)
207
214
 
208
215
  def S_dot(self, v):
209
216
 
@@ -274,7 +281,7 @@ class TDVP:
274
281
  sampleGradients = SampledObs( sampleGradients, p)
275
282
 
276
283
  start_timing(outp, "solve TDVP eqn.")
277
- update, solverResidual = self.solve(Eloc, sampleGradients)
284
+ update, solverResidual, pinvCutoff = self.solve(Eloc, sampleGradients)
278
285
  stop_timing(outp, "solve TDVP eqn.")
279
286
 
280
287
  if outp is not None:
@@ -291,6 +298,7 @@ class TDVP:
291
298
  self.metaData = {
292
299
  "tdvp_error": self._get_tdvp_error(update),
293
300
  "tdvp_residual": solverResidual,
301
+ "pinv_cutoff": pinvCutoff,
294
302
  "SNR": self.snr,
295
303
  "spectrum": self.ev,
296
304
  }
@@ -301,11 +309,11 @@ class TDVP:
301
309
  sampleGradients1 = sampleGradients.subset(start=0, step=2)
302
310
  Eloc2 = Eloc.subset(start=1, step=2)
303
311
  sampleGradients2 = sampleGradients.subset(start=1, step=2)
304
- update_1, _ = self.solve(Eloc1, sampleGradients1)
312
+ update_1, _, _ = self.solve(Eloc1, sampleGradients1)
305
313
  S2, F2 = self.get_tdvp_equation(Eloc2, sampleGradients2)
306
314
 
307
315
  validation_tdvpErr = self._get_tdvp_error(update_1)
308
- update, solverResidual = self.solve(Eloc, sampleGradients)
316
+ update, solverResidual, _ = self.solve(Eloc, sampleGradients)
309
317
  validation_residual = (jnp.linalg.norm(S2.dot(update_1) - F2) / jnp.linalg.norm(F2)) / solverResidual
310
318
 
311
319
  self.crossValidationFactor_residual = validation_residual
@@ -1,2 +1,2 @@
1
1
  """Current jVMC version at head on Github."""
2
- __version__ = "1.2.4"
2
+ __version__ = "1.3.0"
@@ -44,7 +44,6 @@ def eval_batched(batchSize, fun, s):
44
44
 
45
45
  return res[:s.shape[0]]
46
46
 
47
-
48
47
  def flat_gradient(fun, params, arg):
49
48
  gr = grad(lambda p, y: jnp.real(fun.apply(p, y)))(params, arg)["params"]
50
49
  gr = tree_flatten(tree_map(lambda x: x.ravel(), gr))[0]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: jVMC
3
- Version: 1.2.4
3
+ Version: 1.3.0
4
4
  Summary: jVMC: Versatile and performant variational Monte Carlo
5
5
  Home-page: https://jvmc.readthedocs.io/en/latest/#
6
6
  Author: Markus Schmitt, Moritz Reh
@@ -9,8 +9,37 @@ Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
11
  Description-Content-Type: text/markdown
12
- Provides-Extra: dev
13
12
  License-File: LICENSE
13
+ Requires-Dist: setuptools
14
+ Requires-Dist: wheel
15
+ Requires-Dist: numpy
16
+ Requires-Dist: openfermion
17
+ Requires-Dist: jax<=0.4.20,>=0.4.1
18
+ Requires-Dist: jaxlib<=0.4.20,>=0.4.1
19
+ Requires-Dist: flax<=0.6.11,>=0.6.4
20
+ Requires-Dist: mpi4py
21
+ Requires-Dist: h5py
22
+ Requires-Dist: PyYAML
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: scipy<1.13
25
+ Provides-Extra: dev
26
+ Requires-Dist: setuptools; extra == "dev"
27
+ Requires-Dist: wheel; extra == "dev"
28
+ Requires-Dist: numpy; extra == "dev"
29
+ Requires-Dist: openfermion; extra == "dev"
30
+ Requires-Dist: jax<=0.4.20,>=0.4.1; extra == "dev"
31
+ Requires-Dist: jaxlib<=0.4.20,>=0.4.1; extra == "dev"
32
+ Requires-Dist: flax<=0.6.11,>=0.6.4; extra == "dev"
33
+ Requires-Dist: mpi4py; extra == "dev"
34
+ Requires-Dist: h5py; extra == "dev"
35
+ Requires-Dist: PyYAML; extra == "dev"
36
+ Requires-Dist: matplotlib; extra == "dev"
37
+ Requires-Dist: scipy<1.13; extra == "dev"
38
+ Requires-Dist: sphinx; extra == "dev"
39
+ Requires-Dist: mock; extra == "dev"
40
+ Requires-Dist: sphinx_rtd_theme; extra == "dev"
41
+ Requires-Dist: pytest; extra == "dev"
42
+ Requires-Dist: pytest-mpi; extra == "dev"
14
43
 
15
44
  [![Documentation Status](https://readthedocs.org/projects/jvmc/badge/?version=latest)](https://jvmc.readthedocs.io/en/latest/?badge=latest)
16
45
  [![PyPi version](https://badgen.net/pypi/v/jVMC/)](https://pypi.org/project/jVMC/)
@@ -1,25 +1,29 @@
1
1
  setuptools
2
2
  wheel
3
3
  numpy
4
- jax<=0.4.11,>=0.4.1
5
- jaxlib<=0.4.11,>=0.4.1
4
+ openfermion
5
+ jax<=0.4.20,>=0.4.1
6
+ jaxlib<=0.4.20,>=0.4.1
6
7
  flax<=0.6.11,>=0.6.4
7
8
  mpi4py
8
9
  h5py
9
10
  PyYAML
10
11
  matplotlib
12
+ scipy<1.13
11
13
 
12
14
  [dev]
13
15
  setuptools
14
16
  wheel
15
17
  numpy
16
- jax<=0.4.11,>=0.4.1
17
- jaxlib<=0.4.11,>=0.4.1
18
+ openfermion
19
+ jax<=0.4.20,>=0.4.1
20
+ jaxlib<=0.4.20,>=0.4.1
18
21
  flax<=0.6.11,>=0.6.4
19
22
  mpi4py
20
23
  h5py
21
24
  PyYAML
22
25
  matplotlib
26
+ scipy<1.13
23
27
  sphinx
24
28
  mock
25
29
  sphinx_rtd_theme
@@ -7,8 +7,7 @@ with open("./jVMC/version.py") as fp:
7
7
  with open("README.md", "r") as fh:
8
8
  long_description = fh.read()
9
9
 
10
-
11
- DEFAULT_DEPENDENCIES = ["setuptools", "wheel", "numpy", "jax>=0.4.1,<=0.4.11", "jaxlib>=0.4.1,<=0.4.11", "flax>=0.6.4,<=0.6.11", "mpi4py", "h5py", "PyYAML", "matplotlib"]
10
+ DEFAULT_DEPENDENCIES = ["setuptools", "wheel", "numpy", "openfermion", "jax>=0.4.1,<=0.4.20", "jaxlib>=0.4.1,<=0.4.20", "flax>=0.6.4,<=0.6.11", "mpi4py", "h5py", "PyYAML", "matplotlib", "scipy<1.13"] # Scipy version restricted, because jax is currently incompatible with new function namespace scipy.sparse.tril
12
11
  #CUDA_DEPENDENCIES = ["setuptools", "wheel", "numpy", "jax[cuda]>=0.2.11,<=0.2.25", "flax>=0.3.6,<=0.3.6", "mpi4py", "h5py"]
13
12
  DEV_DEPENDENCIES = DEFAULT_DEPENDENCIES + ["sphinx", "mock", "sphinx_rtd_theme", "pytest", "pytest-mpi"]
14
13
 
@@ -1,5 +1,6 @@
1
1
  import unittest
2
-
2
+ import sys
3
+ sys.path.append(sys.path[0] + "../..")
3
4
  import jVMC
4
5
  import jVMC.nets as nets
5
6
 
@@ -68,20 +69,44 @@ class TestSymNet(unittest.TestCase):
68
69
 
69
70
  def test_sym_net_generative(self):
70
71
  L=5
71
- rbm = nets.RNN1DGeneral(L=5)
72
+ rnn = nets.RNN1DGeneral(L=5)
72
73
  orbit = jVMC.util.symmetries.get_orbit_1D(L, "translation")
73
- rbm_sym = nets.SymNet(net=rbm, orbit=orbit)
74
- params = rbm_sym.init(random.PRNGKey(0), jnp.zeros((5,), dtype=np.int32))
74
+ rnn_sym = nets.SymNet(net=rnn, orbit=orbit)
75
+ params = rnn_sym.init(random.PRNGKey(0), jnp.zeros((5,), dtype=np.int32))
75
76
 
76
77
  S0 = jnp.pad(jnp.array([1, 0, 1, 1, 0]), (0, 4), 'wrap')
77
78
  S = jnp.array(
78
79
  [S0[i:i + 5]for i in range(5)]
79
80
  )
80
- psiS = jax.vmap(lambda s: rbm_sym.apply(params, s))(S)
81
+ psiS = jax.vmap(lambda s: rnn_sym.apply(params, s))(S)
81
82
  psiS = psiS - psiS[0]
82
83
 
83
84
  self.assertTrue(jnp.max(jnp.abs(psiS)) < 1e-12)
84
85
 
85
86
 
87
+ class TestCpxNet(unittest.TestCase):
88
+
89
+ def test_cpx_rnn_1d(self):
90
+ rnn = nets.RNN1DGeneral(L=5, realValuedParams=False)
91
+ params = rnn.init(random.PRNGKey(0), jnp.zeros((5,), dtype=np.int32))
92
+
93
+ S0 = jnp.array([1, 0, 1, 1, 0])
94
+ psiS0 = rnn.apply(params, S0)
95
+ self.assertTrue(jnp.max(jnp.abs(psiS0 - (-1.7393452561818394+0.025880153799492975j))) < 1e-12)
96
+
97
+ def test_cpx_rnn_2d(self):
98
+ rnn = nets.RNN2DGeneral(L=4, realValuedParams=False)
99
+ params = rnn.init(random.PRNGKey(0), jnp.zeros((4, 4), dtype=np.int32))
100
+
101
+ S0 = jnp.array(
102
+ [[1, 0, 1, 1],
103
+ [0, 1, 1, 1],
104
+ [0, 0, 1, 0],
105
+ [1, 0, 0, 1]]
106
+ )
107
+ psiS0 = rnn.apply(params, S0)
108
+ self.assertTrue(jnp.max(jnp.abs(psiS0 - (-5.549380111605981-0.0316078980423882j))) < 1e-12)
109
+
110
+
86
111
  if __name__ == "__main__":
87
112
  unittest.main()
@@ -132,6 +132,44 @@ class TestOperator(unittest.TestCase):
132
132
 
133
133
  hamiltonian.compile()
134
134
 
135
+ def test_fermionic_operators(self):
136
+ L = 2
137
+
138
+ rbm = nets.CpxRBM(numHidden=2, bias=True)
139
+ psi = NQS(rbm)
140
+
141
+ sampler = jVMC.sampler.ExactSampler(psi, (L,))
142
+
143
+ def commutator(i,j):
144
+ Comm = op.BranchFreeOperator()
145
+ Comm.add(op.scal_opstr( 1., (op.annihilation(i), op.creation(j), ) ) )
146
+ Comm.add(op.scal_opstr( 1., (op.creation(j), op.annihilation(i), ) ) )
147
+ return Comm
148
+
149
+ observalbes_dict = {
150
+ "same_site": [commutator(0,0),commutator(1,1)],
151
+ "distinct_site": [commutator(0,1),commutator(1,0)]
152
+ }
153
+ out_dict = jVMC.util.util.measure(observalbes_dict, psi, sampler)
154
+
155
+ self.assertTrue(
156
+ jnp.allclose(
157
+ jnp.concatenate(
158
+ (out_dict["same_site"]['mean'],
159
+ out_dict["distinct_site"]['mean'])),
160
+ jnp.array([1.,1.,0.,0.]),
161
+ rtol=1e-15)
162
+ )
163
+
164
+ self.assertTrue(
165
+ jnp.allclose(
166
+ jnp.concatenate(
167
+ (out_dict["same_site"]['variance'],
168
+ out_dict["distinct_site"]['variance'])),
169
+ jnp.array([0.,0.,0.,0.]),
170
+ rtol=1e-15)
171
+ )
172
+
135
173
 
136
174
  if __name__ == "__main__":
137
175
  unittest.main()
@@ -45,7 +45,7 @@ class TestPOVM(unittest.TestCase):
45
45
  self.sampler = jVMC.sampler.ExactSampler(self.psi, (L,), lDim=4, logProbFactor=1)
46
46
 
47
47
  self.tdvpEquation = jVMC.util.tdvp.TDVP(self.sampler, rhsPrefactor=-1.,
48
- svdTol=1e-6, diagonalShift=0, makeReal='real', crossValidation=False)
48
+ pinvTol=0.0, pinvCutoff=1e-6, diagonalShift=0, makeReal='real', crossValidation=False)
49
49
 
50
50
  #self.stepper = jVMC.util.stepper.Euler(timeStep=dt) # ODE integrator
51
51
  self.stepper = jVMC.util.stepper.Heun(timeStep=dt) # ODE integrator
@@ -0,0 +1,111 @@
1
+ import unittest
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+
6
+ import jVMC
7
+ from jVMC.stats import SampledObs
8
+ import jVMC.operator as op
9
+ from jVMC.global_defs import device_count
10
+
11
+
12
+ class TestStats(unittest.TestCase):
13
+
14
+ def test_sampled_obs(self):
15
+
16
+ Obs1Loc = jnp.array([[1, 2, 3]] * device_count())
17
+ Obs2Loc = jnp.array([[[1, 4], [2, 5], [3, 7]]] * device_count())
18
+ p = (1. / (3 * device_count())) * jnp.ones((device_count(), 3))
19
+
20
+ obs1 = SampledObs(Obs1Loc, p)
21
+ obs2 = SampledObs(Obs2Loc, p)
22
+
23
+ self.assertAlmostEqual(obs1.mean()[0], 2.)
24
+ self.assertAlmostEqual(obs1.var()[0], 2./3)
25
+
26
+ self.assertTrue(jnp.allclose(obs2.covar(), jnp.array([[2./3, 1],[1.,14./9]])))
27
+
28
+ self.assertTrue(jnp.allclose(obs2.mean(), jnp.array([2,16./3])))
29
+ self.assertTrue(jnp.allclose(obs1.covar(obs2), jnp.array([2./3,1.])))
30
+
31
+ self.assertTrue(jnp.allclose(obs1.covar(obs2), obs1.covar_data(obs2).mean()))
32
+
33
+ self.assertTrue(jnp.allclose(obs1.covar_var(obs2), obs1.covar_data(obs2).var()))
34
+
35
+ O = obs2._data.reshape((-1,2))
36
+ self.assertTrue(jnp.allclose(obs2.tangent_kernel(), jnp.matmul(O, jnp.conj(jnp.transpose(O)))))
37
+
38
+
39
+ def test_estimator(self):
40
+
41
+ L = 4
42
+
43
+ for rbm in [jVMC.nets.CpxRBM(numHidden=1, bias=False), jVMC.nets.RBM(numHidden=1, bias=False)]:
44
+
45
+ # Set up variational wave function
46
+ orbit = jVMC.util.symmetries.get_orbit_1D(L, "translation", "reflection")
47
+ net = jVMC.nets.sym_wrapper.SymNet(net=rbm, orbit=orbit)
48
+ psi = jVMC.vqs.NQS(net)
49
+
50
+ # Set up MCMC sampler
51
+ # mcSampler = jVMC.sampler.MCSampler(psi, (L,), jax.random.PRNGKey(0), updateProposer=jVMC.sampler.propose_spin_flip, sweepSteps=L+1, numChains=777)
52
+
53
+ exactSampler = jVMC.sampler.ExactSampler(psi, (L,))
54
+
55
+ p0 = psi.parameters
56
+
57
+ # configs, configsLogPsi, p = mcSampler.sample(numSamples=40000)
58
+
59
+ configs, configsLogPsi, p = exactSampler.sample()
60
+
61
+ h = op.BranchFreeOperator()
62
+ for i in range(L):
63
+ h.add(op.scal_opstr(2., (op.Sx(i),)))
64
+ h.add(op.scal_opstr(2., (op.Sy(i), op.Sz((i + 1) % L))))
65
+
66
+ op_estimator = h.get_estimator_function(psi)
67
+
68
+ obs1 = SampledObs(configs, p, estimator=op_estimator)
69
+
70
+ Oloc = h.get_O_loc(configs, psi)
71
+ obs2 = SampledObs(Oloc, p)
72
+ self.assertTrue( jnp.allclose( obs1.mean(p0), obs2.mean() ) )
73
+
74
+ psiGrads = SampledObs(psi.gradients(configs), p)
75
+ Eloc = h.get_O_loc(configs, psi, configsLogPsi)
76
+ Eloc = SampledObs( Eloc, p )
77
+
78
+ Egrad2 = 2*jnp.real( psiGrads.covar(Eloc) )
79
+
80
+ self.assertTrue(jnp.allclose( jnp.real(obs1.mean_and_grad(psi, p0)[1]), Egrad2.ravel() ))
81
+
82
+
83
+ # obs1 = SampledObs(weights=pEx, configs=configsEx, estimator=op_estimator)
84
+ # E0 = obs1.mean(psi.parameters)
85
+ # p0 = psi.get_parameters()
86
+ # dp = 1e-6
87
+ # p0 = p0.at[0].add(dp)
88
+ # psi.set_parameters(p0)
89
+ # configsEx, configsLogPsiEx, pEx = exactSampler.sample(parameters=psi.params)
90
+ # obs1 = SampledObs(weights=pEx, configs=configsEx, estimator=op_estimator)
91
+ # E1 = obs1.mean(psi.parameters)
92
+ # print((E1-E0)/dp)
93
+
94
+ def test_subset_function(self):
95
+
96
+ N = 10
97
+ Obs1 = jnp.reshape(jnp.arange(jax.device_count()*N), (jax.device_count(), N, 1))
98
+ p = jax.random.uniform(jax.random.PRNGKey(123), (jax.device_count(),N))
99
+ p = p / jnp.sum(p)
100
+
101
+ obs1 = SampledObs(Obs1, p)
102
+ obs2 = obs1.subset(0,N//2)
103
+
104
+ self.assertTrue( jnp.allclose(obs1.mean(), jnp.sum(jnp.reshape(Obs1, (jax.device_count(), N)) * p)) )
105
+
106
+ self.assertTrue(obs2.mean() - jnp.sum(jnp.reshape(Obs1, (jax.device_count(), N))[:,0:N//2] * p[:,0:N//2]) / jnp.sum(p[:,0:N//2]))
107
+
108
+
109
+ obs3 = SampledObs(Obs1[:,0:N//2,:], p[:,0:N//2] / jnp.sum(p[:,0:N//2]))
110
+
111
+ self.assertTrue( jnp.allclose(obs3.covar(), obs2.covar()))
@@ -47,7 +47,7 @@ class TestGsSearch(unittest.TestCase):
47
47
  exactSampler = sampler.ExactSampler(psi, L)
48
48
 
49
49
  delta = 2
50
- tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, svdTol=1e-8, rhsPrefactor=1., diagonalShift=delta, makeReal='real')
50
+ tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, pinvTol=0.0, pinvCutoff=1e-8, rhsPrefactor=1., diagonalShift=delta, makeReal='real')
51
51
 
52
52
  # Perform ground state search to get initial state
53
53
  ground_state_search(psi, hamiltonianGS, tdvpEquation, exactSampler, numSteps=100, stepSize=5e-2)
@@ -94,7 +94,7 @@ class TestTimeEvolution(unittest.TestCase):
94
94
  # Set up adaptive time stepper
95
95
  stepper = jVMCstepper.AdaptiveHeun(timeStep=1e-3, tol=1e-5)
96
96
 
97
- tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, svdTol=1e-8, rhsPrefactor=1.j, diagonalShift=0., makeReal='imag')
97
+ tdvpEquation = jVMC.util.TDVP(exactSampler, snrTol=1, pinvTol=0.0, pinvCutoff=1e-8, rhsPrefactor=1.j, diagonalShift=0., makeReal='imag')
98
98
 
99
99
  t = 0
100
100
  obs = []
@@ -1,35 +0,0 @@
1
- import unittest
2
-
3
- import jax
4
- import jax.numpy as jnp
5
-
6
- from jVMC.stats import SampledObs
7
- import jVMC.mpi_wrapper as mpi
8
-
9
-
10
- class TestStats(unittest.TestCase):
11
-
12
- def test_sampled_obs(self):
13
-
14
- Obs1Loc = jnp.array([[1,2,3]])
15
- Obs2Loc = jnp.array([[[1,4],[2,5],[3,7]]])
16
- p = (1./3) * jnp.ones(3)[None,...]
17
-
18
- obs1 = SampledObs(Obs1Loc, p)
19
- obs2 = SampledObs(Obs2Loc, p)
20
-
21
- self.assertAlmostEqual(obs1.mean()[0], 2.)
22
- self.assertAlmostEqual(obs1.var()[0], 2./3)
23
-
24
- self.assertTrue(jnp.allclose(obs2.covar(), jnp.array([[2./3, 1],[1.,14./9]])))
25
-
26
- self.assertTrue(jnp.allclose(obs2.mean(), jnp.array([2,16./3])))
27
- self.assertTrue(jnp.allclose(obs1.covar(obs2), jnp.array([2./3,1.])))
28
-
29
- self.assertTrue(jnp.allclose(obs1.covar(obs2), obs1.covar_data(obs2).mean()))
30
-
31
- self.assertTrue(jnp.allclose(obs1.covar_var(obs2), obs1.covar_data(obs2).var()))
32
-
33
- O = obs2._data.reshape((-1,2))
34
- self.assertTrue(jnp.allclose(obs2.tangent_kernel(), jnp.matmul(O, jnp.conj(jnp.transpose(O)))))
35
-
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes