-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathsvd.cc
More file actions
466 lines (405 loc) · 14.3 KB
/
svd.cc
File metadata and controls
466 lines (405 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <algorithm>
#include "itensor/util/stdx.h"
#include "itensor/tensor/algs.h"
#include "itensor/decomp.h"
#include "itensor/util/print_macro.h"
#include "itensor/itdata/qutil.h"
namespace itensor {
//const auto MAX_INT = std::numeric_limits<int>::max();
using std::swap;
using std::istream;
using std::ostream;
using std::vector;
using std::find;
using std::pair;
using std::make_pair;
using std::string;
using std::sqrt;
using std::move;
using std::tie;
template<typename T>
Spectrum
svdImpl(ITensor const& A,
Index const& uI,
Index const& vI,
ITensor & U,
ITensor & D,
ITensor & V,
Args args)
{
if( args.defined("Minm") )
{
if( args.defined("MinDim") )
{
Global::warnDeprecated("Args Minm and MinDim are both defined. Minm is deprecated in favor of MinDim, MinDim will be used.");
}
else
{
Global::warnDeprecated("Arg Minm is deprecated in favor of MinDim.");
args.add("MinDim",args.getInt("Minm"));
}
}
if( args.defined("Maxm") )
{
if( args.defined("MaxDim") )
{
Global::warnDeprecated("Args Maxm and MaxDim are both defined. Maxm is deprecated in favor of MaxDim, MaxDim will be used.");
}
else
{
Global::warnDeprecated("Arg Maxm is deprecated in favor of MaxDim.");
args.add("MaxDim",args.getInt("Maxm"));
}
}
auto do_truncate = args.getBool("Truncate");
auto thresh = args.getReal("SVDThreshold",1E-3);
auto cutoff = args.getReal("Cutoff",MIN_CUT);
auto maxdim = args.getInt("MaxDim",MAX_DIM);
auto mindim = args.getInt("MinDim",1);
auto doRelCutoff = args.getBool("DoRelCutoff",true);
auto absoluteCutoff = args.getBool("AbsoluteCutoff",false);
auto show_eigs = args.getBool("ShowEigs",false);
auto litagset = getTagSet(args,"LeftTags","Link,U");
auto ritagset = getTagSet(args,"RightTags","Link,V");
if( litagset == ritagset ) Error("In SVD, must specify different tags for the new left and right indices (with Args 'LeftTags' and 'RightTags')");
if(not hasQNs(A))
{
auto M = toMatRefc<T>(A,uI,vI);
Mat<T> UU,VV;
Vector DD;
SVD(M,UU,DD,VV,thresh);
//conjugate VV so later we can just do
//U*D*V to reconstruct ITensor A:
conjugate(VV);
//
// Truncate
//
Vector probs;
if(do_truncate || show_eigs)
{
probs = DD;
for(auto j : range(probs)) probs(j) = sqr(probs(j));
}
Real truncerr = 0;
Real docut_lower = -1;
Real docut_upper = -1;
int ndegen = 1;
long m = DD.size();
if(do_truncate)
{
tie(truncerr,docut_lower,docut_upper,ndegen) = truncate(probs,maxdim,mindim,cutoff,
absoluteCutoff,doRelCutoff,args);
m = probs.size();
resize(DD,m);
reduceCols(UU,m);
reduceCols(VV,m);
}
if(show_eigs)
{
auto showargs = args;
showargs.add("Cutoff",cutoff);
showargs.add("MaxDim",maxdim);
showargs.add("MinDim",mindim);
showargs.add("Truncate",do_truncate);
showargs.add("DoRelCutoff",doRelCutoff);
showargs.add("AbsoluteCutoff",absoluteCutoff);
showEigs(probs,truncerr,A.scale(),showargs);
}
auto uL = Index(m,litagset);
auto vL = setTags(uL,ritagset);
//Fix sign to make sure D has positive elements
Real signfix = (A.scale().sign() == -1) ? -1 : +1;
D = ITensor({uL,vL},
Diag<Real>{DD.begin(),DD.end()},
A.scale()*signfix);
U = ITensor({uI,uL},Dense<T>(move(UU.storage())),LogNum(signfix));
V = ITensor({vI,vL},Dense<T>(move(VV.storage())));
//Square all singular values
//since convention is to report
//density matrix eigs
for(auto& el : DD) el = sqr(el);
#ifdef USESCALE
if(A.scale().isFiniteReal())
{
DD *= sqr(A.scale().real0());
}
else
{
println("Warning: scale not finite real after svd");
}
#endif
return Spectrum(move(DD),{"Truncerr",truncerr});
}
else
{
auto compute_qn = args.getBool("ComputeQNs",false);
auto blocks = doTask(GetBlocks<T>{A.inds(),uI,vI},A.store());
auto Nblock = blocks.size();
if(Nblock == 0) throw ResultIsZero("IQTensor has no blocks");
//TODO: optimize allocation/lookup of Umats,Vmats
// etc. by allocating memory ahead of time (see algs.cc)
// and making Umats a vector of MatrixRef's to this memory
auto Umats = vector<Mat<T>>(Nblock);
auto Vmats = vector<Mat<T>>(Nblock);
//TODO: allocate dvecs in a single allocation
// make dvecs a vector<VecRef>
auto dvecs = vector<Vector>(Nblock);
auto alleig = stdx::reserve_vector<Real>(std::min(dim(uI),dim(vI)));
auto alleigqn = vector<EigQN>{};
if(compute_qn)
{
alleigqn = stdx::reserve_vector<EigQN>(std::min(dim(uI),dim(vI)));
}
if(dim(uI) == 0) throw ResultIsZero("dim(uI) == 0");
if(dim(vI) == 0) throw ResultIsZero("dim(vI) == 0");
for(auto b : range(Nblock))
{
auto& M = blocks[b].M;
auto& UU = Umats.at(b);
auto& VV = Vmats.at(b);
auto& d = dvecs.at(b);
SVD(M,UU,d,VV,thresh);
//conjugate VV so later we can just do
//U*D*V to reconstruct ITensor A:
conjugate(VV);
alleig.insert(alleig.end(),d.begin(),d.end());
if(compute_qn)
{
auto bi = blocks[b].i1;
auto q = qn(uI,1+bi);
for(auto sval : d)
{
alleigqn.emplace_back(sqr(sval),q);
}
}
}
//Square the singular values into probabilities
//(density matrix eigenvalues)
for(auto& sval : alleig) sval = sval*sval;
//Sort all eigenvalues from largest to smallest
//irrespective of quantum numbers
stdx::sort(alleig,std::greater<Real>{});
if(compute_qn) stdx::sort(alleigqn,std::greater<EigQN>{});
auto probs = Vector(move(alleig),VecRange{alleig.size()});
long m = probs.size();
Real truncerr = 0;
Real docut_lower = -1;
Real docut_upper = -1;
int ndegen = 1;
if(do_truncate)
{
tie(truncerr,docut_lower,docut_upper,ndegen) = truncate(probs,maxdim,mindim,cutoff,
absoluteCutoff,doRelCutoff,args);
m = probs.size();
alleigqn.resize(m);
}
if(show_eigs)
{
auto showargs = args;
showargs.add("Cutoff",cutoff);
showargs.add("MaxDim",maxdim);
showargs.add("MinDim",mindim);
showargs.add("Truncate",do_truncate);
showargs.add("DoRelCutoff",doRelCutoff);
showargs.add("AbsoluteCutoff",absoluteCutoff);
showEigs(probs,truncerr,A.scale(),showargs);
}
auto Liq = Index::qnstorage{};
auto Riq = Index::qnstorage{};
Liq.reserve(Nblock);
Riq.reserve(Nblock);
auto total_m = 0;
for(auto b : range(Nblock))
{
auto& d = dvecs.at(b);
auto& B = blocks[b];
decltype(d.size()) this_m = 0;
if(do_truncate)
{
//Keep all eigenvalues above docut_upper
while(this_m < d.size() &&
total_m < m &&
sqr(d(this_m)) > docut_upper)
{
if(d(this_m) < 0) d(this_m) = 0;
++this_m;
++total_m;
}
//Now check if there are any degenerate eigenvalues to keep
//(ones above docut_lower)
while(ndegen > 0 &&
this_m < d.size() &&
total_m < m &&
sqr(d(this_m)) > docut_lower)
{
if(d(this_m) < 0) d(this_m) = 0;
++this_m;
++total_m;
--ndegen;
}
}
else
{
this_m = d.size();
total_m += this_m;
}
if(this_m == 0)
{
d.clear();
B.M.clear();
assert(not B.M);
continue;
}
resize(d,this_m);
qn(uI,1+B.i1);
Liq.emplace_back(qn(uI,1+B.i1),this_m);
Riq.emplace_back(qn(vI,1+B.i2),this_m);
}
#ifdef DEBUG
if(Liq.empty()) throw std::runtime_error("New Index of U after SVD is empty");
if(Riq.empty()) throw std::runtime_error("New Index of V after SVD is empty");
#endif
auto L = Index(move(Liq),uI.dir(),litagset);
auto R = Index(move(Riq),vI.dir(),ritagset);
auto Uis = IndexSet(uI,dag(L));
auto Dis = IndexSet(L,R);
auto Vis = IndexSet(vI,dag(R));
auto Ustore = QDense<T>(Uis,QN());
auto Vstore = QDense<T>(Vis,QN());
auto Dstore = QDiagReal(Dis);
long n = 0;
for(auto b : range(Nblock))
{
auto& B = blocks[b];
auto& UU = Umats.at(b);
auto& VV = Vmats.at(b);
auto& d = dvecs.at(b);
//Default-constructed B.M corresponds
//to this_m==0 case above
if(not B.M) continue;
//println("block b = ",b);
//printfln("{B.i1,n} = {%d,%d}",B.i1,n);
//printfln("{n,n} = {%d,%d}",n,n);
//printfln("{B.i2,n} = {%d,%d}",B.i2,n);
auto uind = Labels(2);
uind[0] = B.i1;
uind[1] = n;
auto pU = getBlock(Ustore,Uis,uind);
assert(pU.data() != nullptr);
assert(uI.blocksize0(B.i1) == long(nrows(UU)));
auto Uref = makeMatRef(pU,uI.blocksize0(B.i1),L.blocksize0(n));
reduceCols(UU,L.blocksize0(n));
Uref &= UU;
auto dind = Labels(2);
dind[0] = n;
dind[1] = n;
auto pD = getBlock(Dstore,Dis,dind);
assert(pD.data() != nullptr);
auto Dref = makeVecRef(pD.data(),d.size());
Dref &= d;
auto vind = Labels(2);
vind[0] = B.i2;
vind[1] = n;
auto pV = getBlock(Vstore,Vis,vind);
assert(pV.data() != nullptr);
assert(vI.blocksize0(B.i2) == long(nrows(VV)));
auto Vref = makeMatRef(pV.data(),pV.size(),vI.blocksize0(B.i2),R.blocksize0(n));
reduceCols(VV,R.blocksize0(n));
//println("Doing Vref &= VV");
//Print(Vref.range());
//Print(VV.range());
Vref &= VV;
/////////DEBUG
//Matrix D(d.size(),d.size());
//for(decltype(d.size()) n = 0; n < d.size(); ++n)
// {
// D(n,n) = d(n);
// }
//D *= A.scale().real0();
//auto AA = Uref * D * transpose(Vref);
//Print(Uref);
//Print(D);
//Print(Vref);
//printfln("Check %d = \n%s",b,AA);
//printfln("Diff %d = %.10f",b,norm(AA-B.M));
/////////DEBUG
++n;
}
//Fix sign to make sure D has positive elements
Real signfix = (A.scale().sign() == -1) ? -1. : +1.;
U = ITensor(Uis,move(Ustore));
D = ITensor(Dis,move(Dstore),A.scale()*signfix);
V = ITensor(Vis,move(Vstore),LogNum{signfix});
//Originally eigs were found without including scale
//so put the scale back in
if(A.scale().isFiniteReal())
{
probs *= sqr(A.scale().real0());
}
else
{
println("Warning: scale not finite real after svd");
}
if(compute_qn)
{
auto qns = stdx::reserve_vector<QN>(alleigqn.size());
for(auto& eq : alleigqn) qns.push_back(eq.qn);
return Spectrum(move(probs),move(qns),{"Truncerr",truncerr});
}
return Spectrum(move(probs),{"Truncerr",truncerr});
}
return Spectrum{};
}
Spectrum
svdOrd2(ITensor const& A,
Index const& uI,
Index const& vI,
ITensor & U,
ITensor & D,
ITensor & V,
Args args)
{
if( args.defined("Maxm") )
{
if( args.defined("MaxDim") )
{
Global::warnDeprecated("Args Maxm and MaxDim are both defined. Maxm is deprecated in favor of MaxDim, MaxDim will be used.");
}
else
{
Global::warnDeprecated("Arg Maxm is deprecated in favor of MaxDim.");
args.add("MaxDim",args.getInt("Maxm"));
}
}
auto do_truncate = args.defined("Cutoff")
|| args.defined("MaxDim");
if(not args.defined("Truncate"))
{
args.add("Truncate",do_truncate);
}
if(A.order() != 2)
{
Error("A must be matrix-like (order 2)");
}
if(isComplex(A))
{
return svdImpl<Cplx>(A,uI,vI,U,D,V,args);
}
return svdImpl<Real>(A,uI,vI,U,D,V,args);
}
} //namespace itensor