Exemplo n.º 1
0
 FiniteSitesDFE(Random & random, DFE dfe, int L): dfe(dfe), U0(dfe.U0), L(L), draw_label(0,L-1), fitness_effects(L,1), sign_flips(L,false){
 
     for(auto & W : fitness_effects){
         W = dfe.get_fitness_effect(random, Clone());
     }
 };
Exemplo n.º 2
0
// Routing table tracking main
void RouteTrackingMain(SESSION *s)
{
	ROUTE_TRACKING *t;
	UINT64 now;
	ROUTE_TABLE *table;
	ROUTE_ENTRY *rs;
	bool changed = false;
	bool check = false;
	bool any_modified = false;
	// Validate arguments
	if (s == NULL)
	{
		return;
	}
	if (s->ClientModeAndUseVLan == false)
	{
		return;
	}

	// Get the state
	t = ((VLAN *)s->PacketAdapter->Param)->RouteState;
	if (t == NULL)
	{
		return;
	}

	// Current time
	PROBE_STR("RouteTrackingMain 1");
	now = Tick64();

	if (t->RouteChange != NULL)
	{
		if (t->NextRouteChangeCheckTime == 0 ||
			t->NextRouteChangeCheckTime <= now)
		{
			t->NextRouteChangeCheckTime = now + 1000ULL;

			check = IsRouteChanged(t->RouteChange);

			if (check)
			{
				Debug("*** Routing Table Changed ***\n");
				t->NextTrackingTime = 0;
			}
		}
	}
	if (t->NextTrackingTime != 0 && t->NextTrackingTime > now)
	{
		if (s->UseUdpAcceleration && s->UdpAccel != NULL && s->UdpAccel->NatT_IP_Changed)
		{
			// Check always if the IP address of the NAT-T server has changed
		}
		else
		{
			PROBE_STR("RouteTrackingMain 2");
			return;
		}
	}
	PROBE_STR("RouteTrackingMain 3");

	if (s->UseUdpAcceleration && s->UdpAccel != NULL)
	{
		IP nat_t_ip;

		s->UdpAccel->NatT_IP_Changed = false;

		Zero(&nat_t_ip, sizeof(nat_t_ip));

		Lock(s->UdpAccel->NatT_Lock);
		{
			Copy(&nat_t_ip, &s->UdpAccel->NatT_IP, sizeof(IP));
		}
		Unlock(s->UdpAccel->NatT_Lock);

		// Add a route to the NAT-T server
		if (IsZeroIp(&nat_t_ip) == false)
		{
			if (t->RouteToNatTServer == NULL)
			{
				if (t->RouteToEight != NULL)
				{
					ROUTE_ENTRY *e = Clone(t->RouteToEight, sizeof(ROUTE_ENTRY));
					char ip_str[64];
					char ip_str2[64];

					Copy(&e->DestIP, &nat_t_ip, sizeof(IP));
					e->Metric = e->OldIfMetric;

					IPToStr(ip_str, sizeof(ip_str), &e->DestIP);
					IPToStr(ip_str2, sizeof(ip_str2), &e->GatewayIP);

					t->RouteToNatTServer = e;

					if (AddRouteEntry(t->RouteToNatTServer))
					{
						Debug("Adding Static Route to %s via %s metric %u: ok.\n", ip_str, ip_str2, e->Metric);
					}
					else
					{
						FreeRouteEntry(t->RouteToNatTServer);
						t->RouteToNatTServer = NULL;
					}
				}
			}
		}
	}

	// Get the current routing table
	table = GetRouteTable();
	rs = t->RouteToServer;
	if (table != NULL)
	{
		UINT i;
		bool route_to_server_erased = true;
		bool is_vlan_want_to_be_default_gateway = false;
		UINT vlan_default_gatewat_metric = 0;
		UINT other_if_default_gateway_metric_min = INFINITE;

		// Get whether the routing table have been changed
		if (t->LastRoutingTableHash != table->HashedValue)
		{
			t->LastRoutingTableHash = table->HashedValue;
			changed = true;
		}

		//DebugPrintRouteTable(table);

		// Scan the routing table
		for (i = 0;i < table->NumEntry;i++)
		{
			ROUTE_ENTRY *e = table->Entry[i];

			if (rs != NULL)
			{
				if (CmpIpAddr(&e->DestIP, &rs->DestIP) == 0 &&
					CmpIpAddr(&e->DestMask, &rs->DestMask) == 0
//					&& CmpIpAddr(&e->GatewayIP, &rs->GatewayIP) == 0
//					&& e->InterfaceID == rs->InterfaceID &&
//					e->LocalRouting == rs->LocalRouting &&
//					e->Metric == rs->Metric
					)
				{
					// Routing entry to the server that added at the time of connection is found
					route_to_server_erased = false;
				}
			}

			// Search for the default gateway
			if (IPToUINT(&e->DestIP) == 0 &&
				IPToUINT(&e->DestMask) == 0)
			{
				Debug("e->InterfaceID = %u, t->VLanInterfaceId = %u\n",
					e->InterfaceID, t->VLanInterfaceId);

				if (e->InterfaceID == t->VLanInterfaceId)
				{
					// The virtual LAN card think that he want to be a default gateway
					is_vlan_want_to_be_default_gateway = true;
					vlan_default_gatewat_metric = e->Metric;

					if (vlan_default_gatewat_metric >= 2 &&
						t->OldDefaultGatewayMetric == (vlan_default_gatewat_metric - 1))
					{
						// Restore because the PPP server rewrites
						// the routing table selfishly
						DeleteRouteEntry(e);
						e->Metric--;
						AddRouteEntry(e);
						Debug("** Restore metric destroyed by PPP.\n");

						any_modified = true;
					}

					// Keep this entry
					if (t->DefaultGatewayByVLan != NULL)
					{
						// Delete if there is one added last time
						FreeRouteEntry(t->DefaultGatewayByVLan);
					}

					t->DefaultGatewayByVLan = ZeroMalloc(sizeof(ROUTE_ENTRY));
					Copy(t->DefaultGatewayByVLan, e, sizeof(ROUTE_ENTRY));

					t->OldDefaultGatewayMetric = vlan_default_gatewat_metric;
				}
				else
				{
					// There are default gateway other than the virtual LAN card
					// Save the metric value of the default gateway
					if (other_if_default_gateway_metric_min > e->Metric)
					{
						// Ignore the metric value of all PPP connection in the case of Windows Vista
						if (MsIsVista() == false || e->PPPConnection == false)
						{
							other_if_default_gateway_metric_min = e->Metric;
						}
						else
						{
							// a PPP is used to Connect to the network
							// in using Windows Vista
							t->VistaAndUsingPPP = true;
						}
					}
				}
			}
		}

		if (t->VistaAndUsingPPP)
		{
			if (t->DefaultGatewayByVLan != NULL)
			{
				if (is_vlan_want_to_be_default_gateway)
				{
					if (t->VistaOldDefaultGatewayByVLan == NULL || Cmp(t->VistaOldDefaultGatewayByVLan, t->DefaultGatewayByVLan, sizeof(ROUTE_ENTRY)) != 0)
					{
						ROUTE_ENTRY *e;
						// Add the route of 0.0.0.0/1 and 128.0.0.0/1
						// to the system if the virtual LAN card should be
						// the default gateway in the case of the connection
						// using PPP in Windows Vista

						if (t->VistaOldDefaultGatewayByVLan != NULL)
						{
							FreeRouteEntry(t->VistaOldDefaultGatewayByVLan);
						}

						if (t->VistaDefaultGateway1 != NULL)
						{
							DeleteRouteEntry(t->VistaDefaultGateway1);
							FreeRouteEntry(t->VistaDefaultGateway1);

							DeleteRouteEntry(t->VistaDefaultGateway2);
							FreeRouteEntry(t->VistaDefaultGateway2);
						}

						t->VistaOldDefaultGatewayByVLan = Clone(t->DefaultGatewayByVLan, sizeof(ROUTE_ENTRY));

						e = Clone(t->DefaultGatewayByVLan, sizeof(ROUTE_ENTRY));
						SetIP(&e->DestIP, 0, 0, 0, 0);
						SetIP(&e->DestMask, 128, 0, 0, 0);
						t->VistaDefaultGateway1 = e;

						e = Clone(t->DefaultGatewayByVLan, sizeof(ROUTE_ENTRY));
						SetIP(&e->DestIP, 128, 0, 0, 0);
						SetIP(&e->DestMask, 128, 0, 0, 0);
						t->VistaDefaultGateway2 = e;

						AddRouteEntry(t->VistaDefaultGateway1);
						AddRouteEntry(t->VistaDefaultGateway2);

						Debug("Vista PPP Fix Route Table Added.\n");

						any_modified = true;
					}
				}
				else
				{
					if (t->VistaOldDefaultGatewayByVLan != NULL)
					{
						FreeRouteEntry(t->VistaOldDefaultGatewayByVLan);
						t->VistaOldDefaultGatewayByVLan = NULL;
					}

					if (t->VistaDefaultGateway1 != NULL)
					{
						Debug("Vista PPP Fix Route Table Deleted.\n");
						DeleteRouteEntry(t->VistaDefaultGateway1);
						FreeRouteEntry(t->VistaDefaultGateway1);

						DeleteRouteEntry(t->VistaDefaultGateway2);
						FreeRouteEntry(t->VistaDefaultGateway2);

						any_modified = true;

						t->VistaDefaultGateway1 = t->VistaDefaultGateway2 = NULL;
					}
				}
			}
		}

		// If the virtual LAN card want to be the default gateway and
		// there is no LAN card with smaller metric of 0.0.0.0/0 than
		// the virtual LAN card, delete other default gateway entries
		// to elect the virtual LAN card as the default gateway
//		Debug("is_vlan_want_to_be_default_gateway = %u, rs = %u, route_to_server_erased = %u, other_if_default_gateway_metric_min = %u, vlan_default_gatewat_metric = %u\n",
//			is_vlan_want_to_be_default_gateway, rs, route_to_server_erased, other_if_default_gateway_metric_min, vlan_default_gatewat_metric);
		if (is_vlan_want_to_be_default_gateway && (rs != NULL && route_to_server_erased == false) &&
			other_if_default_gateway_metric_min >= vlan_default_gatewat_metric)
		{
			// Scan the routing table again
			for (i = 0;i < table->NumEntry;i++)
			{
				ROUTE_ENTRY *e = table->Entry[i];

				if (e->InterfaceID != t->VLanInterfaceId)
				{
					if (IPToUINT(&e->DestIP) == 0 &&
					IPToUINT(&e->DestMask) == 0)
					{
						char str[64];
						// Default gateway is found
						ROUTE_ENTRY *r = ZeroMalloc(sizeof(ROUTE_ENTRY));

						Copy(r, e, sizeof(ROUTE_ENTRY));

						// Put in the queue
						InsertQueue(t->DeletedDefaultGateway, r);

						// Delete this gateway entry once
						DeleteRouteEntry(e);

						IPToStr(str, sizeof(str), &e->GatewayIP);
						Debug("Default Gateway %s Deleted.\n", str);

						any_modified = true;
					}
				}
			}
		}

		if (rs != NULL && route_to_server_erased)
		{
			// Physical entry to the server has disappeared
			Debug("Route to Server entry ERASED !!!\n");

			// Forced disconnection (reconnection enabled)
			s->RetryFlag = true;
			s->Halt = true;
		}

		// Release the routing table
		FreeRouteTable(table);
	}

	// Set the time to perform the next track
	if (t->NextTrackingTimeAdd == 0 || changed)
	{
		t->NextTrackingTimeAdd = TRACKING_INTERVAL_INITIAL;
	}
	else
	{
		UINT64 max_value = TRACKING_INTERVAL_MAX;
		if (t->RouteChange != NULL)
		{
			max_value = TRACKING_INTERVAL_MAX_RC;
		}

		t->NextTrackingTimeAdd += TRACKING_INTERVAL_ADD;

		if (t->NextTrackingTimeAdd >= max_value)
		{
			t->NextTrackingTimeAdd = max_value;
		}
	}
	//Debug("t->NextTrackingTimeAdd = %I64u\n", t->NextTrackingTimeAdd);
	t->NextTrackingTime = now + t->NextTrackingTimeAdd;

	if (any_modified)
	{
		// Clear the DNS cache
		Win32FlushDnsCache();
	}
}
	const CImageAttribute& CImageAttribute::operator=(const CImageAttribute& image)
	{
		Clone(image);
		return *this;
	}
Exemplo n.º 4
0
Object c_Closure::t_bindto(const Variant& newthis, const Variant& scope) {
  if (RuntimeOption::RepoAuthoritative &&
      RuntimeOption::EvalAllowScopeBinding) {
    raise_warning("Closure binding is not supported in RepoAuthoritative mode");
    return Object{};
  }

  auto const cls = getVMClass();
  auto const invoke = cls->getCachedInvoke();

  ObjectData* od = nullptr;
  if (newthis.isObject()) {
    if (invoke->isStatic()) {
      raise_warning("Cannot bind an instance to a static closure");
    } else {
      od = newthis.getObjectData();
    }
  } else if (!newthis.isNull()) {
    raise_warning("Closure::bindto() expects parameter 1 to be object");
    return Object{};
  }

  auto const curscope = invoke->cls();
  auto newscope = curscope;

  if (scope.isObject()) {
    newscope = scope.getObjectData()->getVMClass();
  } else if (scope.isString()) {
    auto const className = scope.getStringData();

    if (!className->equal(s_static.get())) {
      newscope = Unit::loadClass(className);
      if (!newscope) {
        raise_warning("Class '%s' not found", className->data());
        return Object{};
      }
    }
  } else if (scope.isNull()) {
    newscope = nullptr;
  } else {
    raise_warning("Closure::bindto() expects parameter 2 "
                  "to be string or object");
    return Object{};
  }

  if (od && !newscope) {
    // Bound closures should be scoped.  If no scope is specified, scope it to
    // the Closure class.
    newscope = static_cast<Class*>(c_Closure::classof());
  }

  bool thisNotOfCtx = od && !od->getVMClass()->classof(newscope);

  if (!RuntimeOption::EvalAllowScopeBinding) {
    if (newscope != curscope) {
      raise_warning("Re-binding closure scopes is disabled");
      return Object{};
    }

    if (thisNotOfCtx) {
      raise_warning("Binding to objects not subclassed from closure "
                    "context is disabled");
      return Object{};
    }
  }

  c_Closure* clone = Clone(this);
  clone->setClass(nullptr);

  Attr curattrs = invoke->attrs();
  Attr newattrs = static_cast<Attr>(curattrs & ~AttrHasForeignThis);

  if (od) {
    od->incRefCount();
    clone->setThis(od);

    if (thisNotOfCtx) {
      // If the bound $this is not a subclass of the context class, then we
      // have to pessimize translation.
      newattrs |= AttrHasForeignThis;
    }
  } else if (newscope) {
    // If we attach a scope to a function with no bound $this we need to make
    // the function static.
    newattrs |= AttrStatic;
    clone->setClass(newscope);
  }

  // If we are changing either the scope or the attributes of the closure, we
  // need to re-scope its Closure subclass.
  if (newscope != curscope || newattrs != curattrs) {
    assert(newattrs != AttrNone);

    auto newcls = cls->rescope(newscope, newattrs);
    clone->setVMClass(newcls);
  }

  return Object(clone);
}
Exemplo n.º 5
0
 /**
  * This method creates a copy of the current Message. It allocates the new one
  * from the same Message Poll as the original Message and copies a full payload.
  *
  * @returns A pointer to the message or NULL if insufficient message buffers are available.
  */
 Message *Clone(void) const { return Clone(GetLength()); };
Exemplo n.º 6
0
Stack::Stack(const Stack& obj)
{
	stack = nullptr;
	Clone(obj);
}
Exemplo n.º 7
0
void CSL_EfTInt::Apply(MSL_ExprEnv& aEnv, vector<string>& aArgs, vector<string>::iterator& aArgr, CSL_ExprBase& aArg, CSL_ExprBase*& aRes, const string& aReqType)
{
    aRes = Clone();
    aRes->AcceptArg();
    aRes->SetData(aArg.Data());
}
Exemplo n.º 8
0
	UIButton *UIButton::CloneButton()
	{
		return (UIButton *)Clone();
	}
Exemplo n.º 9
0
void skiplightreweightdraw()
{
	float beta  = 0.045;//110/50 = 0.28;//FEXGSP = 0.4
	float gamma = 1.182;//110/50 = 1.24;//FEXGSP = 0.4

	auto f= new TFile("skiplightreweight.root");
	auto h12all = (TH1F *)f->Get("h12all");
	auto h12fcr = (TH1F *)f->Get("h12fcr");
	auto h12fex = (TH1F *)f->Get("h12fex");
	auto h12gsp = (TH1F *)f->Get("h12gsp");
	auto hSLall = (TH1F *)f->Get("hSLall");
	auto hSLfcr = (TH1F *)f->Get("hSLfcr");
	auto hSLfex = (TH1F *)f->Get("hSLfex");
	auto hSLgsp = (TH1F *)f->Get("hSLgsp");
	auto h12data = (TH1F *)f->Get("h12data");
	auto hSLdata = (TH1F *)f->Get("hSLdata");

	auto h12dphiall = (TH1F *)f->Get("h12dphiall");
	auto h12dphifcr = (TH1F *)f->Get("h12dphifcr");
	auto h12dphifex = (TH1F *)f->Get("h12dphifex");
	auto h12dphigsp = (TH1F *)f->Get("h12dphigsp");
	auto hSLdphiall = (TH1F *)f->Get("hSLdphiall");
	auto hSLdphifcr = (TH1F *)f->Get("hSLdphifcr");
	auto hSLdphifex = (TH1F *)f->Get("hSLdphifex");
	auto hSLdphigsp = (TH1F *)f->Get("hSLdphigsp");
	auto h12dphidata = (TH1F *)f->Get("h12dphidata");
	auto hSLdphidata = (TH1F *)f->Get("hSLdphidata");

	auto h12dphiNSall = (TH1F *)f->Get("h12dphiNSall");
	auto h12dphiNSfcr = (TH1F *)f->Get("h12dphiNSfcr");
	auto h12dphiNSfex = (TH1F *)f->Get("h12dphiNSfex");
	auto h12dphiNSgsp = (TH1F *)f->Get("h12dphiNSgsp");
	auto hSLdphiNSall = (TH1F *)f->Get("hSLdphiNSall");
	auto hSLdphiNSfcr = (TH1F *)f->Get("hSLdphiNSfcr");
	auto hSLdphiNSfex = (TH1F *)f->Get("hSLdphiNSfex");
	auto hSLdphiNSgsp = (TH1F *)f->Get("hSLdphiNSgsp");
	auto h12dphiNSdata = (TH1F *)f->Get("h12dphiNSdata");
	auto hSLdphiNSdata = (TH1F *)f->Get("hSLdphiNSdata");


	auto h12ordall = (TH1F *)f->Get("h12ordall");
	auto h12ordfcr = (TH1F *)f->Get("h12ordfcr");
	auto h12ordfex = (TH1F *)f->Get("h12ordfex");
	auto h12ordgsp = (TH1F *)f->Get("h12ordgsp");
	auto hSLordall = (TH1F *)f->Get("hSLordall");
	auto hSLordfcr = (TH1F *)f->Get("hSLordfcr");
	auto hSLordfex = (TH1F *)f->Get("hSLordfex");
	auto hSLordgsp = (TH1F *)f->Get("hSLordgsp");
	auto h12orddata = (TH1F *)f->Get("h12orddata");
	auto hSLorddata = (TH1F *)f->Get("hSLorddata");


	auto h12reweighted = (TH1F *)h12all->Clone("h12reweighted");
	auto hSLreweighted = (TH1F *)hSLall->Clone("hSLreweighted");
	h12reweighted->Reset();h12reweighted->SetTitle("h12reweighted");
	hSLreweighted->Reset();hSLreweighted->SetTitle("hSLreweighted");

	auto h12dphiNSreweighted = (TH1F *)h12dphiNSall->Clone("h12dphiNSreweighted");
	auto hSLdphiNSreweighted = (TH1F *)hSLdphiNSall->Clone("hSLdphiNSreweighted");
	h12dphiNSreweighted->Reset();h12dphiNSreweighted->SetTitle("h12dphiNSreweighted");
	hSLdphiNSreweighted->Reset();hSLdphiNSreweighted->SetTitle("hSLdphiNSreweighted");

	auto h12dphireweighted = (TH1F *)h12dphiall->Clone("h12dphireweighted");
	auto hSLdphireweighted = (TH1F *)hSLdphiall->Clone("hSLdphireweighted");
	h12dphireweighted->Reset();h12dphireweighted->SetTitle("h12dphireweighted");
	hSLdphireweighted->Reset();hSLdphireweighted->SetTitle("hSLdphireweighted");

	auto h12ordreweighted = (TH1F *)h12ordall->Clone("h12ordreweighted");
	auto hSLordreweighted = (TH1F *)hSLordall->Clone("hSLordreweighted");
	h12ordreweighted->Reset();h12ordreweighted->SetTitle("h12ordreweighted");
	hSLordreweighted->Reset();hSLordreweighted->SetTitle("hSLordreweighted");


	h12reweighted->Add(h12fex,h12gsp,beta,gamma);
	h12reweighted->Add(h12fcr);

	hSLreweighted->Add(hSLfex,hSLgsp,beta,gamma);
	hSLreweighted->Add(hSLfcr);

	h12dphireweighted->Add(h12dphifex,h12dphigsp,beta,gamma);
	h12dphireweighted->Add(h12dphifcr);

	hSLdphireweighted->Add(hSLdphifex,hSLdphigsp,beta,gamma);
	hSLdphireweighted->Add(hSLdphifcr);

	h12dphiNSreweighted->Add(h12dphiNSfex,h12dphiNSgsp,beta,gamma);
	h12dphiNSreweighted->Add(h12dphiNSfcr);

	hSLdphiNSreweighted->Add(hSLdphiNSfex,hSLdphiNSgsp,beta,gamma);
	hSLdphiNSreweighted->Add(hSLdphiNSfcr);

	h12ordreweighted->Add(h12ordfex,h12ordgsp,beta,gamma);
	h12ordreweighted->Add(h12ordfcr);

	hSLordreweighted->Add(hSLordfex,hSLordgsp,beta,gamma);
	hSLordreweighted->Add(hSLordfcr);



	Normalize({h12data,h12all,hSLdata,hSLall,
			h12dphiall,hSLdphiall,h12dphidata,hSLdphidata,
			h12dphiNSall,hSLdphiNSall,h12dphiNSdata,hSLdphiNSdata,
			h12ordall,hSLordall,h12orddata,hSLorddata});
	SetMC({h12all,hSLall,h12dphiall,hSLdphiall});

	ploteffectiveentries = false;
	plotymax = 0.12;
	plotylog = false;
	plotputmean = true;
	aktstring+="PF Jets R=0.4";
  	plotsecondline = "p_{T,1}>120GeV,p_{T,2}>30GeV";
  	plotthirdline  = "#Delta#phi>2#pi/3, CSV>0.9";
  	
  	
  	plotfilenameend = "12";
  	DrawCompare(h12data,h12all);
	plotfilenameend = "SL";
  	DrawCompare(hSLdata,hSLall);

	Normalize({h12reweighted,hSLreweighted});
	SetMC({h12reweighted,hSLreweighted});

	plotfilenameend = "12";
	DrawCompare(h12data,h12reweighted);
	plotfilenameend = "SL";
	DrawCompare(hSLdata,hSLreweighted);

	plotfilenameend = "";

	// vector<int> colors = {TColor::GetColor("#FA7200"),
	// 					  TColor::GetColor("#9ACD32"),
	// 					  TColor::GetColor("#0D98BA")};//{kGreen-9, kOrange+1,kBlue+3};

	vector<int> colors = {TColor::GetColor(25,87,5),//18,58,5),
						  TColor::GetColor(255,109,24),//234,117,1),//255,117,24),
						  TColor::GetColor(77,135,232)};//{kGreen-9, kOrange+1,kBlue+3};


	auto h12stack = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack","(P)");
	DrawCompare(h12data,h12stack,"x_{J}");


	h12fex->Scale(beta); h12gsp->Scale(gamma);
	auto h12stack2 = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack2","(W)");
	DrawCompare(h12data,h12stack2,"x_{J}");


	auto hSLstack = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack","(P)");
	DrawCompare(hSLdata,hSLstack,"x_{J}");


	hSLfex->Scale(beta); hSLgsp->Scale(gamma);
	auto hSLstack2 = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack2","(W)");
	DrawCompare(hSLdata,hSLstack2,"x_{J}");





	plotputmean = false;
	plotylog = false;
	plotymax = 1.1;
	plotymin = 1E-5;


	Normalize({hSLordreweighted,h12ordreweighted});
	SetMC({hSLordreweighted,h12ordreweighted});

	DrawCompare(h12orddata,h12ordreweighted);
	DrawCompare(hSLorddata,hSLordreweighted);

	auto h12ordstack = stackhists({h12ordfcr,h12ordfex,h12ordgsp},colors,"h12ordstack","(P)");
	DrawCompare(h12orddata,h12ordstack,"skiplight order");


	h12ordfex->Scale(beta); h12ordgsp->Scale(gamma);
	auto h12ordstack2 = stackhists({h12ordfcr,h12ordfex,h12ordgsp},colors,"h12ordstack2","(W)");
	DrawCompare(h12orddata,h12ordstack2,"skiplight order");


	auto hSLordstack = stackhists({hSLordfcr,hSLordfex,hSLordgsp},colors,"hSLordstack","(P)");
	DrawCompare(hSLorddata,hSLordstack,"skiplight order");


	hSLordfex->Scale(beta); hSLordgsp->Scale(gamma);
	auto hSLordstack2 = stackhists({hSLordfcr,hSLordfex,hSLordgsp},colors,"hSLordstack2","(W)");
	DrawCompare(hSLorddata,hSLordstack2,"skiplight order");






	plotylog = true;
	plotymin = 9999;
	plotputmean = false;
	plotputwidth = true;
	plotymax = 0.5;
	plotthirdline  = "CSV>0.9";

	DrawCompare(h12dphidata,h12dphiall,"#Delta#phi");
	DrawCompare(hSLdphidata,hSLdphiall,"#Delta#phi");


	Normalize({hSLdphireweighted,h12dphireweighted});
	SetMC({hSLdphireweighted,h12dphireweighted});

	DrawCompare(h12dphidata,h12dphireweighted,"#Delta#phi");
	DrawCompare(hSLdphidata,hSLdphireweighted,"#Delta#phi");

	//plotymax = 0.5;

	auto h12dphistack = stackhists({h12dphifcr,h12dphifex,h12dphigsp},colors,"h12dphistack","(P)");
	DrawCompare(h12dphidata,h12dphistack,"#Delta#phi");

	h12dphifex->Scale(beta); h12dphigsp->Scale(gamma);
	auto h12dphistack2 = stackhists({h12dphifcr,h12dphifex,h12dphigsp},colors,"h12dphistack2","(W)");
	DrawCompare(h12dphidata,h12dphistack2,"#Delta#phi");


	auto hSLdphistack = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack","(P)");
	DrawCompare(hSLdphidata,hSLdphistack,"#Delta#phi");

	hSLdphifex->Scale(beta); hSLdphigsp->Scale(gamma);
	auto hSLdphistack2 = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack2","(W)");
	DrawCompare(hSLdphidata,hSLdphistack2,"#Delta#phi");



	plotylog = false;
	plotymax = 0.25;
//only interesting dphi region
	DrawCompare(h12dphiNSdata,h12dphiNSall);
	DrawCompare(hSLdphiNSdata,hSLdphiNSall);


	Normalize({hSLdphiNSreweighted,h12dphiNSreweighted});
	SetMC({hSLdphiNSreweighted,h12dphiNSreweighted});

	DrawCompare(h12dphiNSdata,h12dphiNSreweighted);
	DrawCompare(hSLdphiNSdata,hSLdphiNSreweighted);



	auto h12dphiNSstack = stackhists({h12dphiNSfcr,h12dphiNSfex,h12dphiNSgsp},colors,"h12dphiNSstack","(P)");
	DrawCompare(h12dphiNSdata,h12dphiNSstack,"#Delta#phi");

	h12dphiNSfex->Scale(beta); h12dphiNSgsp->Scale(gamma);
	auto h12dphiNSstack2 = stackhists({h12dphiNSfcr,h12dphiNSfex,h12dphiNSgsp},colors,"h12dphiNSstack2","(W)");
	DrawCompare(h12dphiNSdata,h12dphiNSstack2,"#Delta#phi");


	auto hSLdphiNSstack = stackhists({hSLdphiNSfcr,hSLdphiNSfex,hSLdphiNSgsp},colors,"hSLdphiNSstack","(P)");
	DrawCompare(hSLdphiNSdata,hSLdphiNSstack,"#Delta#phi");

	hSLdphiNSfex->Scale(beta); hSLdphiNSgsp->Scale(gamma);
	auto hSLdphiNSstack2 = stackhists({hSLdphiNSfcr,hSLdphiNSfex,hSLdphiNSgsp},colors,"hSLdphiNSstack2","(W)");
	DrawCompare(hSLdphiNSdata,hSLdphiNSstack2,"#Delta#phi");



// 	int nearsidebin1 = 1;
// 	int nearsidebin2 = hSLdphifex->GetNbinsX()/3;

// 	int awaysidebin1 = hSLdphifex->GetNbinsX()/3*2;
// 	int awaysidebin2 = hSLdphifex->GetNbinsX()-1;

// 	float NnsFEX  = hSLdphifex->Integral(nearsidebin1,nearsidebin2);
// 	float NnsGSP  = hSLdphigsp->Integral(nearsidebin1,nearsidebin2);
// 	float NasFEX  = hSLdphifex->Integral(awaysidebin1,awaysidebin2);
// 	float NasGSP  = hSLdphigsp->Integral(awaysidebin1,awaysidebin2);

// 	float NnsData = hSLdphidata->Integral(nearsidebin1,nearsidebin2);
// 	float NasData = hSLdphidata->Integral(awaysidebin1,awaysidebin2);

// 	float alpha = (NnsData - NnsGSP*(1+NasFEX/NasGSP))/(NnsFEX - NnsGSP*NasFEX/NasGSP); 
// 	float beta2 = ((1-alpha)*NasFEX+NasGSP)/NasGSP;

// if (alpha<0) alpha =0;

// 	cout<<"!!!"<<alpha<<" "<<beta2<<endl;



// 	hSLdphifex->Scale(alpha); hSLdphigsp->Scale(beta2);
// 	auto hSLdphistack2_new = stackhists({hSLdphifcr,hSLdphifex,hSLdphigsp},colors,"hSLdphistack2_new");
// 	DrawCompare(hSLdphidata,hSLdphistack2_new,"#Delta#phi");


// 	cout<<" NasFEX+NasGSP = "<<NasFEX+NasGSP<<" ?= "<<
// 		hSLdphifex->Integral(awaysidebin1,awaysidebin2)+hSLdphigsp->Integral(awaysidebin1,awaysidebin2)<<endl;


// 	ploteffectiveentries = false;
// 	plotymax = 0.12;
// 	plotylog = false;
// 	plotputmean = true;
// 	aktstring+="PF Jets R=0.4";
//   	plotsecondline = "p_{T,1}>120GeV,p_{T,2}>30GeV";
//   	plotthirdline  = "#Delta#phi>2#pi/3, CSV>0.9";






// 	auto h12reweightedtwice = (TH1F *)h12all->Clone("h12reweightedtwice");
// 	auto hSLreweightedtwice = (TH1F *)hSLall->Clone("hSLreweightedtwice");
// 	h12reweightedtwice->Reset();h12reweightedtwice->SetTitle("h12reweightedtwice");
// 	hSLreweightedtwice->Reset();hSLreweightedtwice->SetTitle("hSLreweightedtwice");

// 	h12reweightedtwice->Add(h12fex,h12gsp,alpha,beta2);
// 	h12reweightedtwice->Add(h12fcr);
// 	cout<<"h12reweightedtwice "<<h12reweightedtwice->GetMean()<<endl;

// 	hSLreweightedtwice->Add(hSLfex,hSLgsp,alpha,beta2);
// 	hSLreweightedtwice->Add(hSLfcr);
// 	cout<<"hSLreweightedtwice "<<hSLreweightedtwice->GetMean()<<endl;

// 	Normalize({h12reweightedtwice,hSLreweightedtwice});
// 	SetMC({h12reweightedtwice,hSLreweightedtwice});

// 	plotfilenameend = "12";
// 	DrawCompare(h12data,h12reweightedtwice);
// 	plotfilenameend = "SL";
// 	DrawCompare(hSLdata,hSLreweightedtwice);
// 	plotfilenameend="";



// 	hSLfex->Scale(alpha); hSLgsp->Scale(beta2);
// 	auto hSLstack2_new = stackhists({hSLfcr,hSLfex,hSLgsp},colors,"hSLstack2_new");
// 	DrawCompare(hSLdata,hSLstack2_new,"x_{J}");

// 	h12fex->Scale(alpha); h12gsp->Scale(beta2);
// 	auto h12stack2_new = stackhists({h12fcr,h12fex,h12gsp},colors,"h12stack2_new");
// 	DrawCompare(h12data,h12stack2_new,"x_{J}","___");






}
Exemplo n.º 10
0
void checkclosure()
{
  vector<TH1F *>hsig(Nbins);
  vector<TH1F *>hasd(Nbins);
  vector<TH1F *>hbkg(Nbins);
  vector<TH1F *>hsub(Nbins);
  vector<TH1F *>hhyj(Nbins);
  vector<TH1F *>hshj(Nbins);
  vector<TH1F *>hsbn(Nbins);


  for (int i=0;i<Nbins;i++) {
    seth(10,0,1);
    hsig[i] = geth(Form("hsig%d",i),Form("Signal away-side %s;x_{J}",binnames[i].Data())) ;
    hasd[i] = geth(Form("hasd%d",i),Form("Measured away-side %s;x_{J}",binnames[i].Data()));
    hbkg[i] = geth(Form("hbkg%d",i),Form("Near-side %s;x_{J}",binnames[i].Data()));
    hhyj[i] = geth(Form("hhyj%d",i),Form("Near-side hydjet %s;x_{J}",binnames[i].Data()));
    hsub[i] = geth(Form("hsub%d",i),Form("Subtracted NS %s;x_{J}",binnames[i].Data()));
    hshj[i] = geth(Form("hshj%d",i),Form("Subtracted Hydjet %s;x_{J}",binnames[i].Data()));
    hsbn[i] = geth(Form("hsbn%d",i),Form("Subtracted Naive %s;x_{J}",binnames[i].Data()));
  }




  auto fmcPb = config.getfile_djt("mcPbbfa");

  Fill(fmcPb,{"pthat","weight","jtpt1","refpt1","bProdCode","jtptSL","refptSL","dphiSL1","refparton_flavorForB1","subidSL","bin","pairCodeSL1","discr_csvV1_1","jteta1","jtetaSL"},[&] (dict d) {
      if (d["pthat"]<pthatcut) return;
      
      if (d["jtpt1"]>pt1cut && d["refpt1"]>50 && abs(d["refparton_flavorForB1"])==5 && d["jtptSL"]>pt2cut) {
        int bin = getbinindex(d["bin"]);
        
        float xj = d["jtptSL"]/d["jtpt1"];
        float w = weight1SLPbPb(d);
        if (AwaySide(d)) hasd[bin]->Fill(xj, w);
        if (AwaySide(d) && IsSignal(d)) hsig[bin]->Fill(xj,w);

        if (NearSide(d)) hbkg[bin]->Fill(xj,w);
        if (NearSide(d) && !IsSignal(d)) hhyj[bin]->Fill(xj,w);
      }
        



      });



  for (int i=0;i<Nbins;i++) {
    hsub[i]->Add(hasd[i],hbkg[i],1,-1*bkgfractionInNearSide[i]);
    hsbn[i]->Add(hasd[i],hbkg[i],1,-1);
    hshj[i]->Add(hasd[i],hhyj[i],1,-1);
  }
//  for (int i=0;i<Nbins;i++) 
//    hincsub[i]->Add(hincasd[i],hincbkg[i],1,-1);

  seth(bins);//Nbins,0,100);
  auto hcentrSubSIG = geth("hcentrSubSIG","Signal;bin;#LTx_{J}#GT");
  auto hcentrSubASD = geth("hcentrSubASD","Unsubtracted;bin;#LTx_{J}#GT");

  auto hcentrSubBKS = geth("hcentrSubBKS","Subtracted w/o bkg scaling;bin;#LTx_{J}#GT");
  auto hcentrSubCLS = geth("hcentrSubCLS","Subtracted with bkg scaling;bin;#LTx_{J}#GT");
  auto hcentrSubHJS = geth("hcentrSubHJS","Subtracted Hydjet;bin;#LTx_{J}#GT");


  plotlegendpos = BottomRight;


  for (int i=0;i<Nbins;i++) {
    hcentrSubSIG->SetBinContent(i+1,hsig[i]->GetMean());hcentrSubSIG->SetBinError(i+1,hsig[i]->GetMeanError());
    hcentrSubASD->SetBinContent(i+1,hasd[i]->GetMean());hcentrSubASD->SetBinError(i+1,hasd[i]->GetMeanError());
    hcentrSubBKS->SetBinContent(i+1,hsbn[i]->GetMean());hcentrSubBKS->SetBinError(i+1,hsbn[i]->GetMeanError());

    hcentrSubCLS->SetBinContent(i+1,hsub[i]->GetMean());hcentrSubCLS->SetBinError(i+1,hsub[i]->GetMeanError());
    hcentrSubHJS->SetBinContent(i+1,hshj[i]->GetMean());hcentrSubHJS->SetBinError(i+1,hshj[i]->GetMeanError());

    Draw({hsig[i],hsub[i],hshj[i]});
  }


  plotymin = 0.55;//0.4;
  plotymax = 0.7;//0.8;
  plotlegendpos = BottomRight;
  aktstring = "";


  plotputmean = false;
  //hcentrSubHJS - hydjet only subtraction
  // SetMC({hcentrSubSIG, hcentrSubBKS, hcentrSubASD});
  // SetData({hcentrSubCLS});

  hcentrSubSIG->SetMarkerStyle(kOpenSquare);
  hcentrSubBKS->SetMarkerStyle(kOpenSquare);
  hcentrSubASD->SetMarkerStyle(kOpenSquare);
  hcentrSubCLS->SetMarkerStyle(kFullCircle);


  hcentrSubSIG->SetMarkerColor(TColor::GetColorDark(2)); hcentrSubSIG->SetLineColor(TColor::GetColorDark(2));
  hcentrSubBKS->SetMarkerColor(TColor::GetColorDark(3)); hcentrSubBKS->SetLineColor(TColor::GetColorDark(3));
  hcentrSubASD->SetMarkerColor(TColor::GetColorDark(4)); hcentrSubASD->SetLineColor(TColor::GetColorDark(4));
  hcentrSubCLS->SetMarkerColor(TColor::GetColorDark(3)); hcentrSubCLS->SetLineColor(TColor::GetColorDark(3));

  plotoverwritecolors = false;
  plotlegenddx = -0.15;

  Draw({hcentrSubSIG,hcentrSubASD, hcentrSubBKS, hcentrSubCLS});


  auto syst = (TH1F *)hcentrSubSIG->Clone("syst");
  syst->Add(hcentrSubCLS,-1);
  map<TString,float> m;
  for (unsigned i=0;i<bins.size()-1;i++) {
    float misclosure = syst->GetBinContent(i+1);
    float err = hcentrSubCLS->GetBinError(i+1);
    m[Form("closure%d%d",(int)bins[i],(int)bins[i+1])]=sqrt(misclosure*misclosure+err*err);
  }

  WriteToFile(plotfoldername+"/hydjetclosuresyst.root",m);


}
    pProperties->SetPropertyL(_L8("PropertyName4"), _L8("PropertyValue4"),
                              MSenLayeredProperties::ESenProviderSessionLayer);
    pProperties->SetPropertyL(_L8("PropertyName5"), _L8("PropertyValue5"),
                              MSenLayeredProperties::ESenConsumerSessionLayer);
    pProperties->SetPropertyL(_L8("PropertyName6"), _L8("PropertyValue6"),
                              MSenLayeredProperties::ESenMessageLayer);

    TPtrC8 propertyValue;                              
    pProperties->PropertyL(_L8("PropertyName1"), propertyValue);
                              
    pAsXml = pProperties->AsUtf8LC();
    LOCAL_ASSERT( *pAsXml == KOutputString );
    CleanupStack::PopAndDestroy(pAsXml);

    TInt error;
    pProperties2 = (CSenLayeredHttpTransportProperties*)pProperties->Clone(error);
    LOCAL_ASSERT( error == KErrNone );
    // Destroy cloned properties immediately after cloning
    CleanupStack::PopAndDestroy(pProperties);
    CleanupStack::PushL(pProperties2);

    pAsXml = pProperties2->AsUtf8LC();
    LOCAL_ASSERT( *pAsXml == KOutputString );
    CleanupStack::PopAndDestroy(pAsXml);

    CleanupStack::PopAndDestroy(pProperties2);
    
    CleanupStack::PopAndDestroy(&stringPool);
    
    return KErrNone;
    }
	Local<Value> UnbindOperation::CreateCompletionArg()
	{
		auto a = statement->UnbindParams();
		auto ret = a->Clone();
		return ret;
	}
Exemplo n.º 13
0
int plotUnfoldingMatrixRooUnfold(
		        int analysisIs2D,
			const TString conf,
			DYTools::TRunMode_t runMode=DYTools::NORMAL_RUN,
			DYTools::TSystematicsStudy_t systMode=DYTools::NO_SYST,
			TString rndStudyStr=""
			) {

  const double FSRmassDiff=1.; // largest energy of FSR photon to consider


  // check whether it is a calculation
  if (conf.Contains("_DebugRun_")) {
    std::cout << "plotUnfoldingMatrix: _DebugRun_ detected. Terminating the script\n";
    return retCodeOk;
  }

  // normal calculation
  gBenchmark->Start("makeUnfoldingMatrix");

   {
    DYTools::printExecMode(runMode,systMode);
    const int debug_print=1;
    if (!DYTools::checkSystMode(systMode,debug_print,12,
				DYTools::NO_SYST, DYTools::SYST_RND,
				DYTools::RESOLUTION_STUDY, DYTools::FSR_STUDY,
				DYTools::PU_STUDY,
				DYTools::FSR_5plus, DYTools::FSR_5minus,
				DYTools::PILEUP_5plus, DYTools::PILEUP_5minus,
				//DYTools::ESCALE_STUDY,
				DYTools::ESCALE_RESIDUAL,
				DYTools::FSR_RND_STUDY, DYTools::PU_RND_STUDY))
      return retCodeError;
  }

  if (!DYTools::setup(analysisIs2D)) {
    std::cout << "failed to initialize the analysis\n";
    return retCodeError;
  }

  int escaleResidual_global=1;

  //--------------------------------------------------------------------------------------------------------------
  // Settings
  //==============================================================================================================

  InputFileMgr_t inpMgr;
  InputFileMgr_t *yieldInpMgr=NULL; // needed for ESCALE_RESIDUAL
  if (!inpMgr.Load(conf)) return retCodeError;

  // plotDetResponse uses escale!
  if (systMode==DYTools::ESCALE_RESIDUAL) {
    yieldInpMgr= new InputFileMgr_t(inpMgr);
    // create a temporary object to set proper directories
    EventSelector_t tmpEventSelector(*yieldInpMgr,runMode,
		   DYTools::APPLY_ESCALE,"","",EventSelector::_selectDefault);
    if (escaleResidual_global) {
      inpMgr.rootFileBaseDir("root_files_reg_EScaleResidualGlobal");
      std::cout << "changed rootFileBaseDir to <" << inpMgr.rootFileBaseDir()
		<< ">\n";
    }
  }
  else if (systMode!=DYTools::RESOLUTION_STUDY) {
    // no energy correction for this evaluation
    inpMgr.clearEnergyScaleTag();
  }
  else {
    if (inpMgr.energyScaleTag() == "UNCORRECTED") {
      std::cout << "RESOLUTION_STUDY needs energy scale correction\n";
      return retCodeError;
    }
  }

  // Construct eventSelector, update mgr and plot directory
  TString extraTag=rndStudyStr;
  EventSelector_t evtSelector(inpMgr,runMode,systMode,
			      extraTag, "", EventSelector::_selectDefault);
  evtSelector.setTriggerActsOnData(false);

  // PU and FSR RND studies have to provide the seed externally
  int globalSeed=-1;
  for (int i=0; (globalSeed<=0) && (i<rndStudyStr.Length()); ++i) {
    globalSeed=atoi(rndStudyStr.Data() + i);
  }

  // Event weight handler
  EventWeight_t evWeight;
  int res=evWeight.init(inpMgr.puReweightFlag(),inpMgr.fewzFlag(),
			systMode,rndStudyStr);
  // May 01, 2014: PU weights have to be applied at all steps
  //EventWeight_t evWeightNoPU; // for FSR unfolding weights
  //if (res) res=evWeightNoPU.init(0,inpMgr.fewzFlag(),systMode,rndStudyStr);
  if (!res) {
    std::cout << "failed to prepare weights\n";
    return retCodeError;
  }

  // Prepare output directory
  inpMgr.constDir(systMode,1);


  int seedMin=inpMgr.userKeyValueAsInt("SEEDMIN");
  int seedMax=inpMgr.userKeyValueAsInt("SEEDMAX");
  int dSeed=1;
  int seedDiff=(systMode==DYTools::FSR_STUDY) ? 3 : (seedMax-seedMin+1);

  //std::cout << "seedMin..seedMax=" << seedMin << ".." << seedMax << "\n";

  //return retCodeOk;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code
  //==============================================================================================================


  std::cout << mainpart;

  TRandom random;
  std::vector<ElectronEnergyScale*> escaleV;
  std::vector<EventWeight_t*> specEWeightsV;
  std::vector<double> specReweightsV;
  std::vector<EventSelector_t*> evtSelectorV;
  std::vector<TH2D*> specTH2DWeightV; // used for ESCALE_RESIDUAL

  double specWeight=1.;
  int useSpecWeight=0;
  if (systMode==DYTools::FSR_5plus) { specWeight=1.05; useSpecWeight=1; }
  else if (systMode==DYTools::FSR_5minus) { specWeight=0.95; useSpecWeight=1; }
  else if (systMode==DYTools::FSR_RND_STUDY) useSpecWeight=1;

  // check random seed. Special weights use their own,
  // built-in dependencies on seed
  {
    int startSeed=-1;
    if (systMode==DYTools::SYST_RND) {
      std::cout << "setting startSeed=" << globalSeed << "\n";
      startSeed= globalSeed;
    }
    random.SetSeed(startSeed);
    gRandom->SetSeed(startSeed);
  }

  // The random seeds are needed only if we are running this script in systematics mode

  if (systMode==DYTools::FSR_STUDY) {
    specReweightsV.reserve(seedDiff);
    specEWeightsV.reserve(seedDiff);
    for (int i=0; i<seedDiff; ++i) {
      double specW= 1 + 0.05*(i-1);
      specReweightsV.push_back(specW);
      specEWeightsV.push_back(new EventWeight_t(evWeight));
    }
  }
  else if (systMode==DYTools::PU_STUDY) {
    if (inpMgr.puReweightFlag()==0) {
      std::cout << "systMode=PU_STUDY needs puReweightFlag=1 in the input file\n";
      return retCodeError;
    }
    specEWeightsV.reserve(2);
    for (int i=0; i<2; ++i) {
      DYTools::TSystematicsStudy_t study=(i==0) ? DYTools::PILEUP_5minus : DYTools::PILEUP_5plus;
      EventWeight_t *ew=new EventWeight_t();
      if (!ew->init(inpMgr.puReweightFlag(),inpMgr.fewzFlag(),study,rndStudyStr)) {
	std::cout << "in plotUnfoldingMatrix.C\n";
	return retCodeError;
      }
      specEWeightsV.push_back(ew);
    }
  }
  else if (systMode==DYTools::SYST_RND) {
    // nothing special about weights
  }
  else if (systMode==DYTools::RESOLUTION_STUDY) {
    if (seedMax==-111) {
      seedMin=-111;
      seedMax= 111;
      dSeed=seedMax-seedMin;
      seedDiff=2;
    }
    if (seedMax < seedMin) {
      printf("error: randomSeedMax=%d, seedMin=%d\n",seedMax,seedMin);
      return retCodeError;
    }
    specEWeightsV.reserve(seedDiff); // not used, but needed as a check
    escaleV.reserve(seedDiff);
    for (int i=seedMin; i<=seedMax; i+=dSeed) {
      TString escaleTag=inpMgr.energyScaleTag() +
	TString(Form("_MIRROR_RANDOMIZED%d",i));
      ElectronEnergyScale *ees= new ElectronEnergyScale(escaleTag);
      if (1) {
	std::cout << "randomSeed=" << i << ". EScale=";
	ees->print();
	std::cout<<"\n";
      }
      escaleV.push_back(ees);
      specEWeightsV.push_back(new EventWeight_t(evWeight));
      EventSelector_t *evtSel=new EventSelector_t(evtSelector,ees);
      // correction acts like on data!
      evtSel->setEScaleCorrectionType(DYTools::DATA,DYTools::ESCALE_STUDY_RND);
      //evtSel->editECName().Append(Form("_idx%d",i+seedMin));
      evtSelectorV.push_back(evtSel);
    }
  }

  // prepare tools for ESCALE_RESIDUAL
  TH2D* h2ShapeWeights=NULL;
  if (systMode==DYTools::ESCALE_RESIDUAL) {
    if (!yieldInpMgr) {
      std::cout << "yieldInpMgr had to be created\n";
      return retCodeError;
    }
    DYTools::TSystematicsStudy_t yieldSystMode=DYTools::APPLY_ESCALE;
    TString shapeFName=yieldInpMgr->signalYieldFullFileName(yieldSystMode,1);
    delete yieldInpMgr; // no longer needed
    if (rndStudyStr.Length()) {
      shapeFName.ReplaceAll(TString("__") + rndStudyStr,"");
    }
    TString subdir="ShapeReweight";
    TString field="zeeMCShapeReweight_";
    TString ddBkg=(inpMgr.userKeyValueAsInt("DDBKG")==1) ? "ddBkg" : "mcBkg";
    field.Append(ddBkg);
    std::cout << "Obtaining shape weights from <"
	      << shapeFName << ">"
	      << "(use" << ddBkg << ")\n";
    h2ShapeWeights=LoadHisto2D(field,shapeFName,subdir,1);
    if (!h2ShapeWeights) {
      std::cout << "failed to find histo \"ZeeMCShapeReweight\"\n";
      return retCodeError;
    }
    if ((DYTools::massBinningSet==DYTools::_MassBins_2012) &&
	(DYTools::study2D==1)) {
      HERE("set weights for the underflow bin to 1.");
      int ibin=1;
      for (int jbin=1; jbin<=24; jbin++) {
	h2ShapeWeights->SetBinContent(ibin,jbin, 1.);
	h2ShapeWeights->SetBinError  (ibin,jbin, 0.);
      }
    }
    std::cout << "shapeWeights:\n"; printHisto(h2ShapeWeights);

    int ensembleSize= inpMgr.userKeyValueAsInt("RESIDUAL_STUDY_SIZE");
    if (ensembleSize<=0) ensembleSize=100;
    ensembleSize++;
    std::cout << "EScale_residual ensemble size=" << ensembleSize
	      << " (one added for non-randomized entry)\n";

    std::vector<TString> tmpLabelV; // local variable for testing
    specTH2DWeightV.reserve(ensembleSize);
    tmpLabelV.reserve(ensembleSize);

    specTH2DWeightV.push_back(Clone(h2ShapeWeights,
				    "h2NonRndShapeW","h2NonRndShapeW"));
    tmpLabelV.push_back("NonRndShape");

    if (!escaleResidual_global) {
      TH2D *h2ResApply=Clone(h2ShapeWeights,"h2ResApply");
      // vary randomly and independently in each bin
      // prepare histo for randomization. Assume 10% error on the deviation
      for (int ibin=1; ibin<=h2ResApply->GetNbinsX(); ++ibin) {
	for (int jbin=1; jbin<=h2ResApply->GetNbinsY(); ++jbin) {
	double dev=h2ResApply->GetBinContent(ibin,jbin);
	//h2ResApply->SetBinError(ibin,jbin, 0.1*dev);
	h2ResApply->SetBinError(ibin,jbin, 1.);
	h2ResApply->SetBinError(ibin,jbin, dev);
	}
      }

      HistoPair2D_t hpRnd("hpRnd",h2ResApply);

      for (int i=1; i<ensembleSize; ++i) {
	TString name=Form("rndShapeWeight_%d",i);
	TH2D* h2Rnd=hpRnd.randomizedWithinErr(0,name);
	specTH2DWeightV.push_back(h2Rnd);
	tmpLabelV.push_back(name);
      }
    }
    else { // global variation
      for (int i=1; i<ensembleSize; ++i) {
	double rnd=gRandom->Gaus(0,1.);
	TString name=Form("rndShapeWeight_%d",i);
	TH2D *h2Rnd=Clone(h2ShapeWeights,name);
	for (int ibin=1; ibin<=h2Rnd->GetNbinsX(); ++ibin) {
	  for (int jbin=1; jbin<=h2Rnd->GetNbinsY(); ++jbin) {
	    double shW = h2ShapeWeights->GetBinContent(ibin,jbin);
	    double rndScale= 1 + rnd*(1-shW);
	    h2Rnd->SetBinContent(ibin,jbin, rndScale);
	  }
	}
	specTH2DWeightV.push_back(h2Rnd);
	tmpLabelV.push_back(name);
      }
    }

    if (0) {
      specTH2DWeightV.push_back(h2ShapeWeights);
      tmpLabelV.push_back("original");
      TCanvas *cx= plotProfiles("cx",specTH2DWeightV,tmpLabelV,NULL,1,
				"MC/data shape reweight");
      cx->Update();
      return retCodeStop;
    }
  }

  //
  // Set up histograms
  //
  std::vector<TH1D*> hMassv;
  std::vector<TH1D*> hMassBinsv;
  //TH1D *hSelEvents=NULL;

  // debug distributions: 1GeV bins
  //createAnyH1Vec(hMassv,"hMass_",inpMgr.sampleNames(),2500,0.,2500.,"M_{ee} [GeV]","counts/1GeV");
  createAnyH1Vec(hMassv,"hMass_",inpMgr.mcSampleNames(),1490,10.,1500.,"M_{ee} [GeV]","counts/1GeV");
  // debug distributions for current mass bin
  createBaseH1Vec(hMassBinsv,"hMassBins_",inpMgr.mcSampleNames());
  // debug: accumulate info about the selected events in the samples
  //hSelEvents=createAnyTH1D("hSelEvents","hSelEvents",inpMgr.mcSampleCount(),0,inpMgr.mcSampleCount(),"sampleId","event count");


  /*
  TH1F *hMassDiff   = new TH1F("hMassDiff","", 100, -30, 30);
  TH1F *hMassDiffBB = new TH1F("hMassDiffBB","", 100, -30, 30);
  TH1F *hMassDiffEB = new TH1F("hMassDiffEB","", 100, -30, 30);
  TH1F *hMassDiffEE = new TH1F("hMassDiffEE","", 100, -30, 30);

  // These histograms will contain (gen-reco) difference
  // for each (mass, Y) bin in a flattened format
  TH2F *hMassDiffV = new TH2F("hMassDiffV","",
			      nUnfoldingBins, -0.5, nUnfoldingBins-0.5,
			      100, -50.0, 50.0);
  TH2F *hYDiffV = new TH2F("hYDiffV","",
			   nUnfoldingBins, -0.5, nUnfoldingBins-0.5,
			   100, -5.0, 5.0);
  */

//   TH1F *hMassDiffV[nUnfoldingBins];
//   for(int i=0; i<nUnfoldingBins; i++){
//     sprintf(hname,"hMassDiffV_%d",i);
//     hMassDiffV[i] = new TH1F(hname,"",100,-50,50);
//   }

  UnfoldingMatrix_t detResponse(UnfoldingMatrix::_cDET_Response,"detResponse");
  UnfoldingMatrix_t detResponseExact(UnfoldingMatrix::_cDET_Response,"detResponseExact");
  UnfoldingMatrix_t detResponseReversed(UnfoldingMatrix::_cDET_Response,"detResponseReversed");

  UnfoldingMatrix_t fsrGood(UnfoldingMatrix::_cFSR, "fsrGood");
  UnfoldingMatrix_t fsrExact(UnfoldingMatrix::_cFSR, "fsrExact");
  UnfoldingMatrix_t fsrDET(UnfoldingMatrix::_cFSR_DET,"fsrDET"); // only relevant indices are checked for ini,fin
  UnfoldingMatrix_t fsrDETexact(UnfoldingMatrix::_cFSR_DET,"fsrDETexact"); // all indices are checked
  // a good working version: response matrix and invResponse are modified after the inversion
  UnfoldingMatrix_t fsrDET_good(UnfoldingMatrix::_cFSR_DET,"fsrDETgood");

  // Pretend to have a uniform binning
  RooUnfoldResponse rooUnfDetRes(DYTools::nUnfoldingBins,
				 -0.5,DYTools::nUnfoldingBins-0.5,
				 "rooUnfDetRes","rooUnfDetRes");
  rooUnfDetRes.UseOverflow(true);

  std::vector<UnfoldingMatrix_t*> detRespV;

  if (systMode==DYTools::NO_SYST) {}
  else if (systMode==DYTools::SYST_RND) {
    detRespV.reserve(2);
    for (int ir=0; ir<2; ++ir) {
      TString name=Form("detResponse_seed%d_replica%d",globalSeed,ir);
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix::_cDET_Response,name));
    }
  }
  else if (systMode==DYTools::RESOLUTION_STUDY) {
    detRespV.reserve(escaleV.size());
    for (int i=seedMin; i<=seedMax; i+=dSeed) {
      TString name=Form("detResponse_seed%d",i);
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix::_cDET_Response,name));
    }
  }
  else if (systMode==DYTools::FSR_STUDY) {
    detRespV.reserve(specReweightsV.size());
    for (unsigned int i=0; i<specReweightsV.size(); i++) {
      TString wStr=(i==0) ? Form("0%2.0f",specReweightsV[i]*100.) : Form("%3.0f",specReweightsV[i]*100.);
      TString name=TString("detResponse_") + wStr;
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix::_cDET_Response,name));
    }
  }
  else if (systMode==DYTools::PU_STUDY) {
    if (specEWeightsV.size()!=2) { std::cout << "expected specEWeights.size=2\n"; return retCodeError; }
    detRespV.reserve(specEWeightsV.size());
    for (unsigned int i=0; i<specEWeightsV.size(); i++) {
      TString wStr=(i==0) ? "PU5minus" : "PU5plus";
      TString name=TString("detResponse_") + wStr;
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix::_cDET_Response,name));
    }
  }
  else if (systMode==DYTools::ESCALE_RESIDUAL) {
    unsigned int count=specTH2DWeightV.size();
    detRespV.reserve(count);
    for (unsigned int i=0; i<count; ++i) {
      TString name=Form("detResponse_%s",niceNumber(i,count).Data());
      if (i==0) name="detResponse_0_nonRnd";
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix::_cDET_Response,name));
    }
  }
  /*
  else if (systMode==DYTools::ESCALE_STUDY) {
    detRespV.reserve(escaleV.size());
    for (unsigned int i=0; i<escaleV.size(); ++i) {
      TString name=TString("detResponse_") + escaleV[i]->calibrationSetShortName();
      detRespV.push_back(new UnfoldingMatrix_t(UnfoldingMatrix_t::_cDET_Response,name));
    }
  }
  */
  if (detRespV.size()) {
    std::cout << "names in detRespV:\n";
    for (unsigned int i=0; i<detRespV.size(); ++i) {
      std::cout << "  - " << detRespV[i]->getName() << "\n";
    }
  }

  // check
  if ((systMode==DYTools::RESOLUTION_STUDY) ||
      (systMode==DYTools::FSR_STUDY) ||
      (systMode==DYTools::PU_STUDY)
      //|| (systMode==DYTools::ESCALE_STUDY)
      ) {
    if (//(detRespV.size() != escaleV.size()) ||
	(detRespV.size() != specEWeightsV.size())) {
      std::cout << "error: detRespV.size=" << detRespV.size()
	//<< ", escaleV.size=" << escaleV.size()
	//<< ", specReweightsV.size=" << specReweightsV.size()
		<< ", specEWeightsV.size=" << specEWeightsV.size()
		<< "\n";
      assert(0);
    }
  }

  //
  // Access samples and fill histograms
  //
  AccessOrigNtuples_t accessInfo;

  //
  // loop over samples
  //
  if (DYTools::processData(runMode)) {

  double extraWeightFactor=1.0;
  EventCounterExt_t ecTotal("total");
  for (unsigned int isample=0; isample<inpMgr.mcSampleCount(); ++isample) {
    const CSample_t *mcSample=inpMgr.mcSampleInfo(isample);
    std::cout << "Processing " << mcSample->getLabel() << "..." << std::endl;
    std::cout << " of size " << mcSample->size() << "\n";
    if (mcSample->size()!=1) {
      std::cout << "mcSample->size is expected to be 1\n";
      return retCodeError;
    }

    for (unsigned int ifile=0; ifile<mcSample->size(); ++ifile) {
      // Read input file
      TFile *infile= new TFile(mcSample->getFName(ifile),"read");
      if (!infile || !infile->IsOpen()) {
	TString skimName=inpMgr.convertSkim2Ntuple(mcSample->getFName(ifile));
	std::cout <<  "  .. failed. Trying <" << skimName << ">" << std::endl;
	infile= new TFile(skimName,"read");
      }
      assert(infile->IsOpen());

      // Get the TTrees
      if (!accessInfo.setTree(*infile,"Events",true)) {
	return retCodeError;
      }

      // Find weight for events for this file
      // The first file in the list comes with weight 1*extraWeightFactor,
      // all subsequent ones are normalized to xsection and luminosity
      ULong_t maxEvents = accessInfo.getEntries();
      // to match old version package (DYee 7TeV paper),
      if (inpMgr.userKeyValueAsInt("USE7TEVMCWEIGHT") &&
	  (isample==0) && (ifile==0)) {
	extraWeightFactor=maxEvents / (inpMgr.totalLumi() * inpMgr.mcSampleInfo(0)->getXsec(ifile));
	//extraWeightFactor=maxEvents / inpMgr.mcSampleInfo(0)->getXsec(ifile);
      }
      //std::cout << "extraWeightFactor=" << extraWeightFactor << ", chk=" << (maxEvents0/inpMgr.mcSampleInfo(0)->getXsec(ifile)) << "\n";
      //const double extraWeightFactor=1.0;
      if (! evWeight.setWeight_and_adjustMaxEvents(maxEvents,
						   inpMgr.totalLumi(),
						   mcSample->getXsec(ifile),
						   extraWeightFactor, inpMgr.selectEventsFlag())) {
	std::cout << "adjustMaxEvents failed\n";
	return retCodeError;
      }
      std::cout << "mcSample xsec=" << mcSample->getXsec(ifile) << ", nEntries=" << maxEvents << "\n";

      std::cout << "       -> sample base weight is " << evWeight.baseWeight() << "\n";
      for (unsigned int iSt=0; iSt<specEWeightsV.size(); ++iSt) {
	specEWeightsV[iSt]->setBaseWeight(evWeight);
      }

      // loop through events
      EventCounterExt_t ec(Form("%s_file%d",mcSample->name.Data(),ifile));
      ec.setIgnoreScale(0); // 1 - count events, 0 - take weight in account
      // adjust the scale in the counter
      // if FEWZ weight should be considered, use evWeight.totalWeight() after
      // the FEWZ weight has been identified (see a line below)
      ec.setScale(evWeight.baseWeight());

      std::cout << "numEntries = " << accessInfo.getEntriesFast()
		<< ", " << maxEvents << " events will be used" << std::endl;

      for(ULong_t ientry=0; ientry<maxEvents; ientry++) {
	if (DYTools::isDebugMode(runMode) &&
	    (ientry>ULong_t(1000000)+DYTools::study2D*ULong_t(2000000))) break; // debug option
	//if (DYTools::isDebugMode(runMode) && (ientry>100)) break; // debug option
	printProgress(250000," ientry=",ientry,maxEvents);
	ec.numEvents_inc();

	// Load generator level info
	accessInfo.GetGen(ientry);
	// If the Z->ll leptons are not electrons, discard this event.
	// This is needed for signal MC samples such as Madgraph Z->ll
	// where all 3 lepton flavors are possible
	if (!accessInfo.genLeptonsAreElectrons()) continue;

	// Load event info
	accessInfo.GetInfoEntry(ientry);

	// Adjust event weight
	// .. here "false" = "not data"
	evWeight.set_PU_and_FEWZ_weights(accessInfo,false);
	//evWeightNoPU.set_PU_and_FEWZ_weights(accessInfo,false);
	if (useSpecWeight) {
	  evWeight.setSpecWeightValue(accessInfo,FSRmassDiff,specWeight);
	  //evWeightNoPU.setSpecWeightValue(accessInfo,FSRmassDiff,specWeight);
	}

	// FSR study correction for weight
	if (systMode==DYTools::FSR_STUDY) {
	  for (unsigned int iSt=0; iSt<specEWeightsV.size(); ++iSt) {
	    specEWeightsV[iSt]->setSpecWeightValue(accessInfo,FSRmassDiff,specReweightsV[iSt]);
	  }
	}

	// setup spec weights
	// .. here "false" = "not data"
	for (unsigned int iSt=0; iSt<specEWeightsV.size(); ++iSt) {
	  specEWeightsV[iSt]->set_PU_and_FEWZ_weights(accessInfo,false);
	}

	if (ientry<20) {
	  std::cout << "ientry=" << ientry << ", "; evWeight.Print(0);
	  //printf("reweight=%4.2lf, fewz_weight=%4.2lf,dE_fsr=%+6.4lf\n",reweight,fewz_weight,(gen->mass-gen->vmass));
	  if (systMode!=DYTools::RESOLUTION_STUDY) {
	    for (unsigned int iSt=0; iSt<specEWeightsV.size(); ++iSt) {
	      std::cout << " specEWeight[" << iSt << "] = "; specEWeightsV[iSt]->Print(0); //std::cout << "\n";
	    }
	  }
	  std::cout << "\n";
	}

	// adjust the scale in the counter to include FEWZ
	// (and possibly PU) weight
	//ec.setScale(evWeight.totalWeight());

	FlatIndex_t fiGenPreFsr, fiGenPostFsr;
	fiGenPreFsr.setGenPreFsrIdx(accessInfo);
	fiGenPostFsr.setGenPostFsrIdx(accessInfo);

	// begin FSR unfolding block
	fsrGood.fillIni(fiGenPreFsr , evWeight.totalWeight());
	fsrGood.fillFin(fiGenPostFsr, evWeight.totalWeight());
	if (fiGenPreFsr.isValid() && fiGenPostFsr.isValid()) {
	  fsrGood.fillMigration(fiGenPreFsr, fiGenPostFsr, evWeight.totalWeight());
	  fsrExact.fillIni(fiGenPreFsr , evWeight.totalWeight());
	  fsrExact.fillFin(fiGenPostFsr, evWeight.totalWeight());
	  fsrExact.fillMigration(fiGenPreFsr, fiGenPostFsr, evWeight.totalWeight());
	}

	int preFsrOk=0, postFsrOk=0;
	if (evtSelector.inAcceptancePreFsr(accessInfo) &&
	    fiGenPreFsr.isValid()) {
	  preFsrOk=1;
	  fsrDET     .fillIni(fiGenPreFsr, evWeight.totalWeight());
	  fsrDET_good.fillIni(fiGenPreFsr, evWeight.totalWeight());
	}

	if (evtSelector.inAcceptance(accessInfo) &&
	    fiGenPostFsr.isValid()) {
	  postFsrOk=1;
	  fsrDET     .fillFin(fiGenPostFsr, evWeight.totalWeight());
	  fsrDET_good.fillFin(fiGenPostFsr, evWeight.totalWeight());
	}

	if (preFsrOk && postFsrOk) {
	  fsrDET.fillMigration(fiGenPreFsr, fiGenPostFsr, evWeight.totalWeight());
	  fsrDET_good.fillMigration(fiGenPreFsr, fiGenPostFsr, evWeight.totalWeight());
	  fsrDETexact.fillIni(fiGenPreFsr , evWeight.totalWeight());
	  fsrDETexact.fillFin(fiGenPostFsr, evWeight.totalWeight());
	  fsrDETexact.fillMigration(fiGenPreFsr, fiGenPostFsr, evWeight.totalWeight());
	}
	// end of FSR unfolding block


	// check event trigger
	if (!evtSelector.eventTriggerOk(accessInfo)) {
	  continue; // no trigger accept? Skip to next event...	
	}
	ec.numEventsPassedEvtTrigger_inc();

	// load dielectron array
	accessInfo.GetDielectrons(ientry);

	// loop through dielectrons
	//int pass=0;
	int candCount=0;
	mithep::TDielectron uncorrDielectron;
	for(Int_t i=0; i<accessInfo.dielectronCount(); i++) {
	  mithep::TDielectron *dielectron = accessInfo.editDielectronPtr(i);
	  ec.numDielectrons_inc();

	  // keep unmodified dielectron
	  if (escaleV.size()) uncorrDielectron.restoreEScaleModifiedValues(*dielectron);

	  // escale may modify dielectron! But it should not here
	  if (!evtSelector.testDielectron(dielectron,accessInfo.evtInfoPtr(),&ec)) continue;
	  //pass=1;

          /******** We have a Z candidate! HURRAY! ********/

	  candCount++;
	  ec.numDielectronsPass_inc();
	  if (ec.numDielectronsOkSameSign_inc(dielectron->q_1,dielectron->q_2)) {
	    // same sign event
	  }

	  //
	  // Fill structures for response matrix

	  FlatIndex_t fiReco;
	  fiReco.setRecoIdx(dielectron);

	  // Fill the matrix of post-FSR generator level invariant mass and rapidity
	  double diWeight=evWeight.totalWeight();
	  detResponse.fillIni(fiGenPostFsr, diWeight);
	  detResponse.fillFin(fiReco      , diWeight);

	  int bothFIValid=fiGenPostFsr.isValid() && fiReco.isValid();
	  if (bothFIValid) {
	    ec.numDielectronsGoodMass_inc();
	    detResponse.fillMigration(fiGenPostFsr, fiReco, diWeight);

	    detResponseExact.fillIni(fiGenPostFsr, diWeight);
	    detResponseExact.fillFin(fiReco      , diWeight);
	    detResponseExact.fillMigration(fiGenPostFsr, fiReco, diWeight);
	  }

	  if (fiGenPostFsr.isValid()) {
	    if (fiReco.isValid()) {
	      rooUnfDetRes.Fill(fiReco.idx(),fiGenPostFsr.idx(), diWeight);
	    }
	    else {
	      rooUnfDetRes.Miss(fiGenPostFsr.idx(), diWeight);
	    }
	  }
	  else rooUnfDetRes.Fake(fiReco.idx(), diWeight);

	  detResponseReversed.fillIni(fiReco,       diWeight);
	  detResponseReversed.fillFin(fiGenPostFsr, diWeight);
	  if (bothFIValid) {
	    detResponseReversed.fillMigration(fiReco,fiGenPostFsr, diWeight);
	  }

	  if (systMode != DYTools::RESOLUTION_STUDY) {
	    switch(systMode) {
	    case DYTools::SYST_RND: {
	      double rnd=gRandom->Gaus(0,1.);
	      if (rnd==double(0.)) rnd=gRandom->Gaus(0,1.);
	      int idx=(rnd<double(0.)) ? 0:1;
	      detRespV[idx]->fillIni( fiGenPostFsr, diWeight );
	      detRespV[idx]->fillFin( fiReco      , diWeight );
	      if (bothFIValid) {
		detRespV[idx]->fillMigration( fiGenPostFsr, fiReco, diWeight);
	      }
	    }
	      break;

	    case DYTools::ESCALE_RESIDUAL:
	      for (unsigned int iSt=0; iSt<detRespV.size(); ++iSt) {
		const TH2D *h2Rnd= specTH2DWeightV[iSt];
		double w=1.;
		if (fiReco.isValid()) {
		  w=h2Rnd->GetBinContent(fiReco.iM()+1,fiReco.iY()+1);
		  if ((iSt==0) && (ientry<20)) {
		    std::cout << "dielectron(M,Y)=" << dielectron->mass
			      << "," << dielectron->y << ", fiReco="
			      << fiReco << ", specWeight=" << w << "\n";
		  }
		}
		double studyWeight= diWeight * w;
		detRespV[iSt]->fillIni( fiGenPostFsr, studyWeight );
		detRespV[iSt]->fillFin( fiReco      , studyWeight );
		if (bothFIValid) {
		  detRespV[iSt]->fillMigration( fiGenPostFsr, fiReco,
						studyWeight);
		}
	      }
	      break;

	    default:
	      for (unsigned int iSt=0; iSt<detRespV.size(); ++iSt) {
		double studyWeight=specEWeightsV[iSt]->totalWeight();
		detRespV[iSt]->fillIni( fiGenPostFsr, studyWeight );
		detRespV[iSt]->fillFin( fiReco      , studyWeight );
		if (bothFIValid) {
		  detRespV[iSt]->fillMigration( fiGenPostFsr, fiReco,
						studyWeight );
		}
	      }
	    }
	  }

	  if (escaleV.size() && (systMode==DYTools::RESOLUTION_STUDY)) {
	    for (unsigned int iESc=0; iESc<escaleV.size(); ++iESc) {
	      dielectron->restoreEScaleModifiedValues(uncorrDielectron);
	      if (evtSelectorV[iESc]->testDielectron(dielectron,
						accessInfo.evtInfoPtr())) {
		FlatIndex_t fiRecoMdf;
		fiRecoMdf.setRecoIdx(dielectron);
		detRespV[iESc]->fillIni(fiGenPostFsr, diWeight);
		detRespV[iESc]->fillFin(fiRecoMdf   , diWeight);
		if (fiGenPostFsr.isValid() && fiRecoMdf.isValid()) {
		  detRespV[iESc]->fillMigration(fiGenPostFsr,fiRecoMdf,
						diWeight);
		}
	      }
	    }
	  }

	  /*
	  Bool_t isB1 = DYTools::isBarrel(dielectron->scEta_1);
	  Bool_t isB2 = DYTools::isBarrel(dielectron->scEta_2);

	  hMassDiff->Fill(massResmeared - gen->mass);
	  if( isB1 && isB2 )
	    hMassDiffBB->Fill(massResmeared - gen->mass);
	  if( (isB1 && !isB2) || (!isB1 && isB2) )
	    hMassDiffEB->Fill(massResmeared - gen->mass);
	  if( !isB1 && !isB2 )
	    hMassDiffEE->Fill(massResmeared - gen->mass);

	  hMassDiffV->Fill(iIndexFlatGen, massResmeared - gen->mass);
	  hYDiffV   ->Fill(iIndexFlatGen, dielectron->y - gen->y);
	  // 	if(iIndexFlatGen != -1){
	  // 	  hMassDiffV[iIndexFlatGen]->Fill(massResmeared - gen->mass);
	  // 	}
	  */

	} // end loop over dielectrons
	if (candCount>1) ec.numMultiDielectronsOk_inc();

      } // end loop over events
      infile->Close();
      delete infile;
      std::cout << ec << "\n";
      ecTotal.add(ec);
    } // end loop over files
    std::cout << "total counts : " << ecTotal << "\n";

  } // loop over iSample
  } // runMode


  UnfoldingMatrix_t fsrDETcorrections(UnfoldingMatrix::_cFSR_DETcorrFactors,"fsrCorrFactors");

  if (DYTools::processData(runMode)) {
    // Compute the errors on the elements of migration matrix
    detResponse.finalizeDetMigrationErr();
    detResponseExact.finalizeDetMigrationErr();
    detResponseReversed.finalizeDetMigrationErr();
    fsrGood.finalizeDetMigrationErr();
    fsrExact.finalizeDetMigrationErr();
    fsrDET.finalizeDetMigrationErr();
    fsrDETexact.finalizeDetMigrationErr();
    fsrDET_good.finalizeDetMigrationErr();
    for (unsigned int i=0; i<detRespV.size(); ++i) detRespV[i]->finalizeDetMigrationErr();

  // Find response matrix, which is simply the normalized migration matrix
    std::cout << "find response matrix" << std::endl;
    detResponse.computeResponseMatrix();
    detResponseExact.computeResponseMatrix();
    detResponseReversed.computeResponseMatrix();
    fsrGood.computeResponseMatrix();
    fsrExact.computeResponseMatrix();
    fsrDET.computeResponseMatrix();
    fsrDETexact.computeResponseMatrix();
    fsrDET_good.computeResponseMatrix();
    for (unsigned int i=0; i<detRespV.size(); ++i) detRespV[i]->computeResponseMatrix();

    std::cout << "find inverted response matrix" << std::endl;
    detResponse.invertResponseMatrix();
    detResponseExact.invertResponseMatrix();
    detResponseReversed.invertResponseMatrix();
    fsrGood.invertResponseMatrix();
    fsrExact.invertResponseMatrix();
    fsrDET.invertResponseMatrix();
    fsrDETexact.invertResponseMatrix();
    fsrDET_good.invertResponseMatrix();
    for (unsigned int i=0; i<detRespV.size(); ++i) detRespV[i]->invertResponseMatrix();

    fsrDETcorrections.prepareFsrDETcorrFactors(fsrDET,fsrDETexact);
    //fsrDETcorrections.printYields();

    std::cout << "finalize fsrDET_good" << std::endl;
    fsrGood.modifyDETResponseMatrices(fsrExact);
    fsrDET_good.modifyDETResponseMatrices(fsrDETexact);

    std::cout << "prepare flat-index arrays" << std::endl;
    detResponse.prepareFIArrays();
    detResponseExact.prepareFIArrays();
    detResponseReversed.prepareFIArrays();
    fsrGood.prepareFIArrays();
    fsrExact.prepareFIArrays();
    fsrDET.prepareFIArrays();
    fsrDETexact.prepareFIArrays();
    fsrDET_good.prepareFIArrays();
    fsrDETcorrections.prepareFIArrays();
    for (unsigned int i=0; i<detRespV.size(); ++i) detRespV[i]->prepareFIArrays();
  }

  //
  // Store constants and reference arrays in files
  //
  if (DYTools::processData(runMode))  std::cout << "store constants in a file" << std::endl;

  //TString outFile=inpMgr.correctionFullFileName("unfolding",systMode,0);
  TString outputDir=inpMgr.constDir(systMode,0);

  //int saveIdxMin=-1;
  TString fnameTag=UnfoldingMatrix_t::generateFNameTag(systMode,globalSeed);
  /*
  {
    TString u="_";
    switch(systMode) {
    case DYTools::NO_SYST:
      fnameTag=DYTools::analysisTag;
      break;
    case DYTools::SYST_RND:
      fnameTag=TString("_replica_") + DYTools::analysisTag;
      //saveIdxMin=0;
     //fnameTag+=seed;
       break;
    case DYTools::RESOLUTION_STUDY:
      fnameTag=TString("_seed_") + DYTools::analysisTag;
      //fnameTag+=seed;
      break;
    case DYTools::FSR_STUDY:
      fnameTag=TString("_fsrStudy_") + DYTools::analysisTag;
      //fnameTag=TString("_reweight_") + DYTools::analysisTag;
      //fnameTag+= int(100*reweightFsr);
      break;
    case DYTools::PU_STUDY:
      fnameTag=TString("_puStudy_") + DYTools::analysisTag;
      break;
    case DYTools::ESCALE_STUDY:
      fnameTag=DYTools::analysisTag+TString("_escale") + u;
      break;
    case DYTools::ESCALE_RESIDUAL:
      fnameTag=DYTools::analysisTag+TString("_escaleResidual");
      break;
    default:
      std::cout<<"requested mode not recognized when determining fnameTag"<<std::endl;
      assert(0);
    }
  }
  */
  if (DYTools::isDebugMode(runMode)) fnameTag.Prepend("_DebugRun_");
  std::cout << "fnameTag=<" << fnameTag << ">\n";
  CPlot::sOutDir.Append(fnameTag);
  CPlot::sOutDir.ReplaceAll(DYTools::analysisTag,"");
  CPlot::sOutDir.Append(DYTools::analysisTag);

  TString callingMacro="plotUnfoldingMatrix.systMode=";
  callingMacro.Append(SystematicsStudyName(systMode));

  if (DYTools::processData(runMode)) {
    if (//(systMode!=DYTools::NORMAL_RND) &&
	(systMode!=DYTools::RESOLUTION_STUDY) &&
	//(systMode!=DYTools::FSR_STUDY) &&
	(systMode!=DYTools::ESCALE_STUDY)) {
      detResponse.autoSaveToFile(outputDir,fnameTag,callingMacro);  // detResponse, reference mc arrays
      detResponseExact.autoSaveToFile(outputDir,fnameTag,callingMacro);
      detResponseReversed.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrGood.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrExact.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrDET.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrDETexact.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrDET_good.autoSaveToFile(outputDir,fnameTag,callingMacro);
      fsrDETcorrections.autoSaveToFile(outputDir,fnameTag,callingMacro);
    }

    TString fname=Form("rooUnfDetRes_%s.root",DYTools::analysisTag.Data());
    if (DYTools::isDebugMode(runMode))
      fname.ReplaceAll(".root","_DebugRun.root");
    TFile fout(fname,"recreate");
    if (!fout.IsOpen()) {
      std::cout << "failed to create the file <" << fout.GetName() << ">\n";
      return retCodeError;
    }
    rooUnfDetRes.Write();
    writeBinningArrays(fout,"plotUnfoldingMatrixRooUnfold");
    std::cout << "file <" << fout.GetName() << "> created\n";
    fout.Close();

    for (unsigned int i=0; i<detRespV.size(); i++)
      detRespV[i]->autoSaveToFile(outputDir,fnameTag,callingMacro);

    // additional saving for systematics
    if (systMode==DYTools::FSR_STUDY) {
      detRespV[0]->autoSaveToFile(inpMgr.constDir(DYTools::FSR_5minus,0),
	  UnfoldingMatrix_t::generateFNameTag(DYTools::FSR_5minus,globalSeed),
				  callingMacro);
      detRespV[2]->autoSaveToFile(inpMgr.constDir(DYTools::FSR_5plus,0),
	  UnfoldingMatrix_t::generateFNameTag(DYTools::FSR_5plus,globalSeed),
				  callingMacro);
    }
    else if (systMode==DYTools::PU_STUDY) {
      TString dir0=inpMgr.constDir(DYTools::PILEUP_5minus,0);
      TString tag0=UnfoldingMatrix_t::generateFNameTag(DYTools::PILEUP_5minus,
						       globalSeed);
      TString dir1=inpMgr.constDir(DYTools::PILEUP_5plus,0);
      TString tag1=UnfoldingMatrix_t::generateFNameTag(DYTools::PILEUP_5plus,
						       globalSeed);
      detRespV[0]->autoSaveToFile(dir0,tag0,callingMacro);
      detRespV[1]->autoSaveToFile(dir1,tag1,callingMacro);
    }
  }
  else {
    if (//(systMode!=DYTools::NORMAL_RND) &&
	(systMode!=DYTools::RESOLUTION_STUDY) &&
	//(systMode!=DYTools::FSR_STUDY) &&
	(systMode!=DYTools::ESCALE_STUDY)) {
      if (!detResponse.autoLoadFromFile(outputDir,fnameTag) ||
	  !detResponseExact.autoLoadFromFile(outputDir,fnameTag) ||
	  !detResponseReversed.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrGood.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrExact.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrDET.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrDETexact.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrDET_good.autoLoadFromFile(outputDir,fnameTag) ||
	  !fsrDETcorrections.autoLoadFromFile(outputDir,fnameTag)) {
	std::cout << "loading failed\n";
	return retCodeError;
      }
    }
    for (unsigned int i=0; i<detRespV.size(); i++) detRespV[i]->autoLoadFromFile(outputDir,fnameTag);
  }


  UnfoldingMatrix_t detRespAvg(detResponse.kind, "detResponseAvg");
  if (1 && detRespV.size()) { //computeAverage
    const double weight=1/double(detRespV.size());
    for (unsigned int i=0; i<detRespV.size(); ++i) {
      TString name=Form("tmp_%d",i);
      UnfoldingMatrix_t tmp(*detRespV[i],name);
      tmp.squareDetMigrationErr();
      detRespAvg.addMigration(tmp,weight);
    }
    detRespAvg.finalizeDetMigrationErr();
    detRespAvg.computeResponseMatrix();
    detRespAvg.invertResponseMatrix();
    detRespAvg.prepareFIArrays();
    detRespAvg.autoSaveToFile(outputDir,fnameTag,callingMacro); // detResponse, reference mc arrays
  }


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================

  /*
  std::cout << "making plots" << std::endl;

  TString unfoldingConstFileName, yieldsFileName;
  detResponse.getFileNames(outputDir,fnameTag, unfoldingConstFileName, yieldsFileName);
  TString unfoldingConstantsPlotFName=unfoldingConstFileName;
  unfoldingConstantsPlotFName.Replace(unfoldingConstantsPlotFName.Index(".root"),
				      sizeof(".root"),
				      "_plots.root");
  TFile *fPlots=new TFile(unfoldingConstantsPlotFName,"recreate");
  if (!fPlots) {
    std::cout << "failed to create a file <" << unfoldingConstantsPlotFName << ">\n";
  }

#ifdef CrossSection_HH
  if (1) {  // study Ini and Fin vecs
    std::vector<VXSectD_t*> dataV;
    TString canvName="canvChk";
    TString fewzTag=(useFewzWeights) ? "_withFEWZ" : "_noFEWZ";
    if (useFewzWeights && regularizeFEWZ) fewzTag="_withMdfFEWZ";
    canvName.Append(fewzTag);
    const int twoPads=0;
    TCanvas *c=new TCanvas(canvName,canvName,600*(1+twoPads),600);
    if (twoPads) {
      c->Divide(2,1);
      c->GetPad(1)->SetLogx(1);
      c->GetPad(2)->SetLogx(1);
      c->GetPad(1)->SetLogy(1);
      c->GetPad(2)->SetLogy(1);
    }
    else { c->SetLogx(1); c->SetLogy(1); }
    int ok=1;

    TH1F *hGenAvg=new TH1F("hGenAvg","hGenAvg",DYTools::nMassBins,DYTools::massBinLimits);
    TH1F *hRecAvg=new TH1F("hRecAvg","hRecAvg",DYTools::nMassBins,DYTools::massBinLimits);
    hGenAvg->SetDirectory(0);
    hRecAvg->SetDirectory(0);
    hGenAvg->Sumw2();
    hRecAvg->Sumw2();

    TH1F *hGenAvg_chk=NULL; //new TH1F("hGenAvg_chk","hGenAvg_chk",DYTools::nMassBins,DYTools::massBinLimits);
    TH1F *hRecAvg_chk=NULL; //new TH1F("hRecAvg_chk","hRecAvg_chk",DYTools::nMassBins,DYTools::massBinLimits);
    if (ok && hGenAvg_chk && hRecAvg_chk) {
      hGenAvg_chk->SetDirectory(0);
      hRecAvg_chk->SetDirectory(0);
      VXSectD_t d("yields_repAvg",DYTools::nUnfoldingBinsMax);
      TString matrixFName,yieldsFName;
      detRespAvg.getFileNames(outputDir,fnameTag, matrixFName,yieldsFName);
      ok=d.Load(matrixFName,"yieldsMcPostFsrGenFIArray","yieldsMcPostFsrRecFIArray","");
      if (ok) ok= (d.FillHisto(hGenAvg_chk,1) && d.FillHistoWithError(hRecAvg_chk));
    }

    for (unsigned int i=0; ok && (i<detRespV.size()); ++i) {
      TString name=Form("yields_rep%d",i);
      VXSectD_t *d=new VXSectD_t(name,DYTools::nUnfoldingBinsMax);
      dataV.push_back(d);
      TString matrixFName,yieldsFName;
      detRespV[i]->getFileNames(outputDir,fnameTag, matrixFName,yieldsFName);
      ok=d->Load(matrixFName,"yieldsMcPostFsrGenFIArray","yieldsMcPostFsrRecFIArray","");
      if (!ok) continue;
      TString hGenName=Form("hGen_rep%d",i);
      TString hRecName=Form("hRec_rep%d",i);
      TH1F *hGen=new TH1F(hGenName,hGenName,DYTools::nMassBins,DYTools::massBinLimits);
      TH1F *hRec=new TH1F(hRecName,hRecName,DYTools::nMassBins,DYTools::massBinLimits);
      hGen->SetDirectory(0);
      hRec->SetDirectory(0);
      if (i==0) {
	hGen->SetTitle(hGen->GetTitle() + fewzTag);
	hRec->SetTitle(hRec->GetTitle() + fewzTag);
      }
      ok= (d->FillHisto(hGen,1) && d->FillHistoWithError(hRec));
      if (!ok) continue;
      hGenAvg->Add(hGen,1/double(detRespV.size()));
      hRecAvg->Add(hRec,1/double(detRespV.size()));
      TString opt="L";
      if (i>0) opt.Append("same");
      int color = i%(50-20) + 20;
      hGen->SetLineColor(color);
      hRec->SetLineColor(color);
      hGen->GetYaxis()->SetRangeUser(5.,3.e6);
      hRec->GetYaxis()->SetRangeUser(5.,3.e6);
      if (twoPads) c->cd(1);
      hGen->Draw(opt);
      if (twoPads) c->cd(2);
      else { if (i==0) opt.Append("same"); }
      hRec->Draw(opt);
    }
    hGenAvg->SetLineColor(kAzure+1);
    hRecAvg->SetLineColor(kRed+1);
    if (twoPads) c->cd(1);
    hGenAvg->Draw("L same");
    if (hGenAvg_chk) hGenAvg_chk->Draw("L same");
    if (twoPads) c->cd(2);
    hRecAvg->Draw("L same");
    if (hRecAvg_chk) hRecAvg_chk->Draw("L same");
    c->Update();
    return;
  }
#endif


  TCanvas *c = MakeCanvas("canvZmass1","canvZmass1",800,600);

  // string buffers
  char ylabel[50];   // y-axis label

  //
  // Draw DY candidate mass at the reconstruction level. Extra
  // smearing is applied. This figure allows one to judge the
  // correctness of the weights aplied to different samples from the
  // smoothness of the combined result.
  //
  sprintf(ylabel,"a.u. / %.1f GeV/c^{2}",hZMassv[0]->GetBinWidth(1));
  CPlot plotZMass1("zmass1","","m(ee) [GeV/c^{2}]",ylabel);
  for(UInt_t i=0; i<fnamev.size(); i++) {
    plotZMass1.AddHist1D(hZMassv[i],labelv[i],"hist",colorv[i],linev[i]);
  }
  plotZMass1.SetLogy();
  plotZMass1.Draw(c);
  SaveCanvas(c,"zmass1");
//   plotZMass1.Draw(c,doSave,format);
//   if (fPlots) { fPlots->cd(); c->Write(); }

  //
  // Draw a plot that illustrates the detector resolution effects.
  // We plot (gen-rec)/gen as a function of mass and rapidity.
  //
  TMatrixD resolutionEffect(DYTools::nMassBins,DYTools::nYBinsMax);
  resolutionEffect = 0;
  for(int i=0; i < resolutionEffect.GetNrows(); i++){
    for(int j=0; j < resolutionEffect.GetNcols(); j++){
      double ngen = (*detResponse.yieldsIni)(i,j);
      double nrec = (*detResponse.yieldsFin)(i,j);
      if( ngen != 0 )
	resolutionEffect(i,j) = (ngen-nrec)/ngen;
    }
  }
  resolutionEffect.Print();
  PlotMatrixVariousBinning(resolutionEffect, "resolution_effect", "LEGO2", NULL);

  //
  // Draw a plot that illustrates the losses due to reconstruction
  // We plot (preFsrExact-preFsr)/preFsrExact as a
  // function of mass and rapidity.
  //
  TMatrixD *unfRecoEffect=detResponseExact.getReconstructionEffect(detResponse);
  unfRecoEffect->Print();
  PlotMatrixVariousBinning(*unfRecoEffect, "reconstruction_effect", "LEGO2", NULL);
  delete unfRecoEffect;

  TMatrixD *unfFsrDETRecoEffect=fsrDETexact.getReconstructionEffect(fsrDET);

  PlotMatrixVariousBinning(*unfFsrDETRecoEffect, "reconstruction_effect_fsrDET", "LEGO2", NULL);
  delete unfFsrDETRecoEffect;

  */

  // Plot response and inverted response matrices
  //std::vector<TH2F*> hResponseV, hInvResponseV;
  //std::vector<TCanvas*> canvV;
  //std::vector<CPlot*> cpResponseV;

  //TH2F *hR, *hIR;
  //TCanvas *e2;
  //CPlot *cpR, *cpIR;
  detResponse.prepareHResponse();
  fsrGood.prepareHResponse();
  fsrExact.prepareHResponse();
  fsrDET.prepareHResponse();
  fsrDETexact.prepareHResponse();
  fsrDET_good.prepareHResponse();

  for (unsigned int iESc=0; iESc<detRespV.size(); ++iESc) {
    detRespV[iESc]->prepareHResponse();
  }

  /*
  // Create a plot of detector resolution without mass binning
  TCanvas *g = MakeCanvas("canvMassDiff","canvMassDiff",600,600);
  CPlot plotMassDiff("massDiff","","reco mass - gen post-FSR mass [GeV/c^{2}]","a.u.");
  hMassDiffBB->Scale(1.0/hMassDiffBB->GetSumOfWeights());
  hMassDiffEB->Scale(1.0/hMassDiffEB->GetSumOfWeights());
  hMassDiffEE->Scale(1.0/hMassDiffEE->GetSumOfWeights());
  plotMassDiff.AddHist1D(hMassDiffBB,"EB-EB","hist",kBlack);
  plotMassDiff.AddHist1D(hMassDiffEB,"EE-EB","hist",kBlue);
  plotMassDiff.AddHist1D(hMassDiffEE,"EE-EE","hist",kRed);
  plotMassDiff.Draw(g);
  SaveCanvas(g,"massDiff");
//   if (fPlots) g->Write();

  // Create a plot of reco - gen post-FSR mass and rapidity difference
  TCanvas *h1 = MakeCanvas("canvMassDiffV","canvMassDiffV",600,600);
  CPlot plotMassDiffV("massDiffV","",
		      "flat index",
		      "reco mass - gen post-FSR mass [GeV/c^{2}]");
  plotMassDiffV.AddHist2D(hMassDiffV,"LEGO");
  plotMassDiffV.Draw(h1);
  SaveCanvas(h1,"hMassDiffV");

  // Create a plot of reco - gen post-FSR mass and rapidity difference
  TCanvas *h2 = MakeCanvas("canvYDiffV","canvYDiffV",600,600);
  CPlot plotYDiffV("massDiffV","",
		      "flat index",
		      "reco Y - gen post-FSR Y");
  plotYDiffV.AddHist2D(hYDiffV,"LEGO");
  plotYDiffV.Draw(h2);
  SaveCanvas(h2,"hYDiffV");

  if (fPlots) {
    fPlots->Close();
    delete fPlots;
    std::cout << "plots saved to a file <" << unfoldingConstantsPlotFName << ">\n";
  }

  //draw errors of Unfolding matrix
  TCanvas *cErrorsResp = MakeCanvas("cErrorsResp","detResponse.DetInvertedResponseErr", 600,600);
  detResponse.DetInvertedResponseErr->Draw("LEGO2");
  cErrorsResp->Update();
  SaveCanvas(cErrorsResp,"cErrorsResp");

  TCanvas *cFsrErrorsResp = MakeCanvas("cErrorsFsr","fsr__.DetInvertedResponseErr", 1200, 600);
  cFsrErrorsResp->Divide(2,1);
  cFsrErrorsResp->cd(1);
  fsrExact.DetInvertedResponseErr->Draw("LEGO2");
  cFsrErrorsResp->cd(2);
  fsrDET.DetInvertedResponseErr->Draw("LEGO2");
  SaveCanvas(cFsrErrorsResp,"cErrorsFsr");



  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //==============================================================================================================
  cout << endl;
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << endl;

  detResponse.printConditionNumber();
  fsrExact.printConditionNumber();
  fsrDET.printConditionNumber();
  fsrDETexact.printConditionNumber();

  if (0) {
    //detResponse.printMatrices();
    //fsr.printMatrices();
    //fsrDET.printMatrices();
    fsrDET_Mdf.printMatrices();
    fsrDET_good.printMatrices();
  }

  //Print errors of the Unfolding matrix when they exceed 0.1
  /
  for (int iM=0; iM<DYTools::nMassBins; iM++)
    for (int iY=0; iY<DYTools::nYBins[iM]; iY++)
      for (int jM=0; jM<DYTools::nMassBins; jM++)
        for (int jY=0; jY<DYTools::nYBins[jM]; jY++)
          {
	    int i=DYTools::findIndexFlat(iM,iY);
	    int j=DYTools::findIndexFlat(jM,jY);
             if (DetInvertedResponseErr(i,j)>0.1)
                {
                   std::cout<<"DetInvertedResponseErr("<<i<<","<<j<<")="<<DetInvertedResponseErr(i,j);
                   std::cout<<", DetInvertedResponse("<<i<<","<<j<<")="<<DetInvertedResponse(i,j)<<std::endl;
                   std::cout<<"(iM="<<iM<<", iY="<<iY<<", jM="<<jM<<", jY="<<jY<<")"<<std::endl<<std::endl;
                }
             if (DetInvertedResponseErr2(i,j)>0.1)
                {
                   std::cout<<"DetInvertedResponseErr2("<<i<<","<<j<<")="<<DetInvertedResponseErr2(i,j);
                   std::cout<<", DetInvertedResponse("<<i<<","<<j<<")="<<DetInvertedResponse(i,j)<<std::endl;
                   std::cout<<"(iM="<<iM<<", iY="<<iY<<", jM="<<jM<<", jY="<<jY<<")"<<std::endl<<std::endl;
                }
          }
  /

  /
  if (0) {
    // Printout of all constants, uncomment if needed
    //printf("DetCorrFactor:\n"); DetCorrFactor.Print();
    printf("DetMigration:\n"); DetMigration.Print();
    printf("DetResponse:\n"); DetResponse.Print();

    printf("DetInvertedResponse:\n"); DetInvertedResponse.Print();
    //printf("DetInvertedResponseErr:\n"); DetInvertedResponseErr.Print();
    //printf("DetResponseArr:\n"); DetResponseArr.Print();
    //printf("DetInvertedResponseArr:\n"); DetInvertedResponseArr.Print();
    //printf("DetInvertedResonseErrArr:\n"); DetInvertedResponseErrArr.Print();

    //   printf("Detector corr factor numerator:\n");
    //   DetCorrFactorNumerator.Print();

    printf("yieldsMcPostFsrGen:\n");
    yieldsMcPostFsrGen.Print();

    printf("yieldsMcPostFsrRec:\n");
    yieldsMcPostFsrRec.Print();


    //   printf("Detector corr factor denominator:\n");
    //   DetCorrFactorDenominator.Print();
    //   printf("yieldsMcPostFsrRecArr:\n");
    //   yieldsMcPostFsrRecArr.Print();

    //printf("yieldsMcGen:\n");
    //yieldsMcGen.Print();
  }
  /

  if (0) {
    detResponse.printYields();
    fsrExact.printYields();
    fsrDET.printYields();
  }
*/
  //gBenchmark->Show("makeUnfoldingMatrix");
  ShowBenchmarkTime("makeUnfoldingMatrix");
  return retCodeOk;
}
Exemplo n.º 14
0
// パケットヘッダをコピーする
PKT *ClonePacket(PKT *p, bool copy_data)
{
	PKT *ret;
	// 引数チェック
	if (p == NULL)
	{
		return NULL;
	}

	ret = ZeroMallocFast(sizeof(PKT));
	ret->PacketSize = p->PacketSize;

	// MAC ヘッダのコピー
	ret->MacHeader = MallocFast(sizeof(MAC_HEADER));
	Copy(ret->MacHeader, p->MacHeader, sizeof(MAC_HEADER));

	// MAC フラグのコピー
	ret->BroadcastPacket = p->BroadcastPacket;
	ret->InvalidSourcePacket = p->InvalidSourcePacket;

	// IPv6 関係構造体のコピー
	Copy(&ret->IPv6HeaderPacketInfo, &p->IPv6HeaderPacketInfo, sizeof(IPV6_HEADER_PACKET_INFO));
	Copy(&ret->ICMPv6HeaderPacketInfo, &p->ICMPv6HeaderPacketInfo, sizeof(ICMPV6_HEADER_INFO));

	// Layer 3
	ret->TypeL3 = p->TypeL3;
	switch (ret->TypeL3)
	{
	case L3_ARPV4:
		// ARP パケット
		ret->L3.ARPv4Header = MallocFast(sizeof(ARPV4_HEADER));
		Copy(ret->L3.ARPv4Header, p->L3.ARPv4Header, sizeof(ARPV4_HEADER));
		break;

	case L3_IPV4:
		// IPv4 パケット
		ret->L3.IPv4Header = MallocFast(sizeof(IPV4_HEADER));
		Copy(ret->L3.IPv4Header, p->L3.IPv4Header, sizeof(IPV4_HEADER));
		break;

	case L3_IPV6:
		// IPv6 パケット
		ret->L3.IPv6Header = MallocFast(sizeof(IPV6_HEADER));
		Copy(ret->L3.IPv6Header, p->L3.IPv6Header, sizeof(IPV6_HEADER));

		ret->IPv6HeaderPacketInfo.IPv6Header = Clone(p->IPv6HeaderPacketInfo.IPv6Header,
			sizeof(IPV6_HEADER));

		ret->IPv6HeaderPacketInfo.HopHeader = Clone(p->IPv6HeaderPacketInfo.HopHeader,
			sizeof(IPV6_OPTION_HEADER));

		ret->IPv6HeaderPacketInfo.EndPointHeader = Clone(p->IPv6HeaderPacketInfo.EndPointHeader,
			sizeof(IPV6_OPTION_HEADER));

		ret->IPv6HeaderPacketInfo.RoutingHeader = Clone(p->IPv6HeaderPacketInfo.RoutingHeader,
			sizeof(IPV6_OPTION_HEADER));

		ret->IPv6HeaderPacketInfo.FragmentHeader = Clone(p->IPv6HeaderPacketInfo.FragmentHeader,
			sizeof(IPV6_FRAGMENT_HEADER));

		ret->IPv6HeaderPacketInfo.Payload = Clone(p->IPv6HeaderPacketInfo.Payload,
			p->IPv6HeaderPacketInfo.PayloadSize);
		break;
	}

	// Layer 4
	ret->TypeL4 = p->TypeL4;
	switch (ret->TypeL4)
	{
	case L4_ICMPV4:
		// ICMPv4 パケット
		ret->L4.ICMPHeader = MallocFast(sizeof(ICMP_HEADER));
		Copy(ret->L4.ICMPHeader, p->L4.ICMPHeader, sizeof(ICMP_HEADER));
		break;

	case L4_ICMPV6:
		// ICMPv6 パケット
		ret->L4.ICMPHeader = MallocFast(sizeof(ICMP_HEADER));
		Copy(ret->L4.ICMPHeader, p->L4.ICMPHeader, sizeof(ICMP_HEADER));

		ret->ICMPv6HeaderPacketInfo.Data = Clone(p->ICMPv6HeaderPacketInfo.Data,
			p->ICMPv6HeaderPacketInfo.DataSize);

		ret->ICMPv6HeaderPacketInfo.EchoData = Clone(p->ICMPv6HeaderPacketInfo.EchoData,
			p->ICMPv6HeaderPacketInfo.EchoDataSize);

		switch (ret->ICMPv6HeaderPacketInfo.Type)
		{
		case ICMPV6_TYPE_ECHO_REQUEST:
		case ICMPV6_TYPE_ECHO_RESPONSE:
			break;

		case ICMPV6_TYPE_ROUTER_SOLICIATION:
			ret->ICMPv6HeaderPacketInfo.Headers.RouterSoliciationHeader =
				Clone(p->ICMPv6HeaderPacketInfo.Headers.RouterSoliciationHeader,
				sizeof(ICMPV6_ROUTER_SOLICIATION_HEADER));
			break;

		case ICMPV6_TYPE_ROUTER_ADVERTISEMENT:
			ret->ICMPv6HeaderPacketInfo.Headers.RouterAdvertisementHeader =
				Clone(p->ICMPv6HeaderPacketInfo.Headers.RouterAdvertisementHeader,
				sizeof(ICMPV6_ROUTER_ADVERTISEMENT_HEADER));
			break;

		case ICMPV6_TYPE_NEIGHBOR_SOLICIATION:
			ret->ICMPv6HeaderPacketInfo.Headers.NeighborSoliciationHeader =
				Clone(p->ICMPv6HeaderPacketInfo.Headers.NeighborSoliciationHeader,
				sizeof(ICMPV6_NEIGHBOR_SOLICIATION_HEADER));
			break;

		case ICMPV6_TYPE_NEIGHBOR_ADVERTISEMENT:
			ret->ICMPv6HeaderPacketInfo.Headers.NeighborAdvertisementHeader =
				Clone(p->ICMPv6HeaderPacketInfo.Headers.NeighborAdvertisementHeader,
				sizeof(ICMPV6_NEIGHBOR_ADVERTISEMENT_HEADER));
			break;
		}

		CloneICMPv6Options(&ret->ICMPv6HeaderPacketInfo.OptionList,
			&p->ICMPv6HeaderPacketInfo.OptionList);
		break;

	case L4_TCP:
		// TCP パケット
		ret->L4.TCPHeader = MallocFast(sizeof(TCP_HEADER));
		Copy(ret->L4.TCPHeader, p->L4.TCPHeader, sizeof(TCP_HEADER));
		break;

	case L4_UDP:
		// UDP パケット
		ret->L4.UDPHeader = MallocFast(sizeof(UDP_HEADER));
		Copy(ret->L4.UDPHeader, p->L4.UDPHeader, sizeof(UDP_HEADER));
		break;
	}

	// Layer 7
	ret->TypeL7 = p->TypeL7;
	switch (ret->TypeL7)
	{
	case L7_DHCPV4:
		// DHCP パケット
		ret->L7.DHCPv4Header = MallocFast(sizeof(DHCPV4_HEADER));
		Copy(ret->L7.DHCPv4Header, p->L7.DHCPv4Header, sizeof(DHCPV4_HEADER));
		break;
	}

	// アドレスデータ
	ret->MacAddressSrc = ret->MacHeader->SrcAddress;
	ret->MacAddressDest = ret->MacHeader->DestAddress;

	if (copy_data)
	{
		// パケット本体もコピー
		ret->PacketData = MallocFast(p->PacketSize);
		Copy(ret->PacketData, p->PacketData, p->PacketSize);
	}

	return ret;
}
Exemplo n.º 15
0
// Parse the SSTP packet
SSTP_PACKET *SstpParsePacket(UCHAR *data, UINT size)
{
	SSTP_PACKET *p;
	USHORT len;
	// Validate arguments
	if (data == NULL || size == 0)
	{
		return NULL;
	}

	if (size < 4)
	{
		return NULL;
	}

	p = ZeroMalloc(sizeof(SSTP_PACKET));

	// Version
	p->Version = *((UCHAR *)data);
	data++;
	size--;

	if (p->Version != SSTP_VERSION_1)
	{
		// Invalid version
		SstpFreePacket(p);
		return NULL;
	}

	// Flag
	if ((*((UCHAR *)data)) & 0x01)
	{
		p->IsControl = true;
	}
	data++;
	size--;

	// Length
	len = READ_USHORT(data) & 0xFFF;
	data += sizeof(USHORT);
	size -= sizeof(USHORT);

	if (len < 4)
	{
		// Invalid size
		SstpFreePacket(p);
		return NULL;
	}

	if (((UINT)(len - 4)) > size)
	{
		// Oversized
		SstpFreePacket(p);
		return NULL;
	}

	// Data
	p->DataSize = len - 4;
	p->Data = Clone(data, p->DataSize);

	if (p->IsControl)
	{
		// Parse the Attribute list
		p->AttibuteList = SstpParseAttributeList(p->Data, p->DataSize, p);

		if (p->AttibuteList == NULL)
		{
			// Failure of parsing list
			SstpFreePacket(p);
			return NULL;
		}
	}

	return p;
}
Exemplo n.º 16
0
//==================================================================
void SimplePrimitiveBase::Split( Hider &hider, bool uSplit, bool vSplit )
{
	DASSERT( IsUsed() );

	if ( mSplitCnt > 9 )
	{
		// $$$ too many splits !!!
		(void)mSplitCnt;
		return;
	}

	if ( uSplit )
	{
		// U split
		SimplePrimitiveBase *pPrimsSU[2] =
		{
			Clone(),
			Clone()
		};
		float	uMid = (mURange[0] + mURange[1]) * 0.5f;
		pPrimsSU[0]->mURange[1] = uMid;
		pPrimsSU[1]->mURange[0] = uMid;
		hider.InsertSplitted( pPrimsSU[0], *this );
		hider.InsertSplitted( pPrimsSU[1], *this );

		if ( vSplit )
		{
			// optional V split
			float	vMid = (mVRange[0] + mVRange[1]) * 0.5f;

			// check.. because we can't be sure that the primitive didn't fail
			// at insertion time
			for (size_t i=0; i < 2; ++i)
			{
				if ( pPrimsSU[i]->IsUsed() )
				{
					SimplePrimitiveBase *pNewPrim = pPrimsSU[i]->Clone();
					pPrimsSU[i]->mVRange[1] = vMid;
					pNewPrim->mVRange[0] = vMid;
					hider.InsertSplitted( pNewPrim, *pPrimsSU[i] );
				}
			}
		}
	}
	else
	{
		// exclusive V split
		if ( vSplit )
		{
			SimplePrimitiveBase *pPrim1 = Clone();
			SimplePrimitiveBase *pPrim2 = Clone();
			
			float	vMid = (mVRange[0] + mVRange[1]) * 0.5f;
			pPrim1->mVRange[1] = vMid;
			pPrim2->mVRange[0] = vMid;

			hider.InsertSplitted( pPrim1, *this );
			hider.InsertSplitted( pPrim2, *this );
		}
	}
}
Exemplo n.º 17
0
Stack& Stack::operator = (const Stack& obj)
{
	if(this != &obj)
		Clone(obj);
	return *this;
}
Exemplo n.º 18
0
CPDF_Object* CPDF_Object::CloneRef(CPDF_IndirectObjectHolder* pDoc) const {
  if (m_ObjNum) {
    return new CPDF_Reference(pDoc, m_ObjNum);
  }
  return Clone();
}
Exemplo n.º 19
0
Arquivo: xsm.c Projeto: aosm/X11
void
CloseDownClient(ClientRec *client)
{
    int index_deleted = 0;

    if (verbose) {
	printf ("ICE Connection closed, IceConn fd = %d\n",
		IceConnectionNumber (client->ice_conn));
	printf ("\n");
    }

    SmsCleanUp (client->smsConn);
    IceSetShutdownNegotiation (client->ice_conn, False);
    IceCloseConnection (client->ice_conn);

    client->ice_conn = NULL;
    client->smsConn = NULL;

    if (!shutdownInProgress && client_info_visible)
    {
	for (index_deleted = 0;
	    index_deleted < numClientListNames; index_deleted++)
	{
	    if (clientListRecs[index_deleted] == client)
		break;
	}
    }

    ListSearchAndFreeOne (RunningList, (char *) client);

    if (saveInProgress)
    {
	Status delStatus = ListSearchAndFreeOne (
	    WaitForSaveDoneList, (char *) client);

	if (delStatus)
	{
	    ListAddLast (FailedSaveList, (char *) client);
	    client->freeAfterBadSavePopup = True;
	}

	ListSearchAndFreeOne (WaitForInteractList, (char *) client);
	ListSearchAndFreeOne (WaitForPhase2List, (char *) client);

	if (delStatus && ListCount (WaitForSaveDoneList) == 0)
	{
	    if (ListCount (FailedSaveList) > 0 && !checkpoint_from_signal)
		PopupBadSave ();
	    else
		FinishUpSave ();
	}
	else if (ListCount (WaitForInteractList) > 0 &&
	    OkToEnterInteractPhase ())
	{
	    LetClientInteract (ListFirst (WaitForInteractList));
	}
	else if (!phase2InProgress &&
	    ListCount (WaitForPhase2List) > 0 && OkToEnterPhase2 ())
	{
	    StartPhase2 ();
	}
    }

    if (client->restartHint == SmRestartImmediately && !shutdownInProgress)
    {
	Clone (client, True /* use saved state */);

	ListAddLast (RestartImmedList, (char *) client);
    }
    else if (client->restartHint == SmRestartAnyway)
    {
	ListAddLast (RestartAnywayList, (char *) client);
    }
    else if (!client->freeAfterBadSavePopup)
    {
	FreeClient (client, True /* free props */);
    }

    if (shutdownInProgress)
    {
	if (ListCount (RunningList) == 0)
	    EndSession (0);
    }
    else if (client_info_visible)
    {
	UpdateClientList ();

	if (current_client_selected == index_deleted)
	{
	    if (current_client_selected == numClientListNames)
		current_client_selected--;

	    if (current_client_selected >= 0)
	    {
		XawListHighlight (clientListWidget, current_client_selected);
		ShowHint (clientListRecs[current_client_selected]);
		if (client_prop_visible)
		{
		    DisplayProps (clientListRecs[current_client_selected]);
		}
	    }
	}
	else
	{
	    if (index_deleted < current_client_selected)
		current_client_selected--;
	    XawListHighlight (clientListWidget, current_client_selected);
	}
    }
}
Exemplo n.º 20
0
/** Defines a column for a property.
 *
 * The following code defines an empty view with three properties:
 * @code
 *  c4_IntProp p1, p2, p3;
 *  c4_View myView = (p1, p2, p3);
 * @endcode
 * @return the new view object (without any data rows)
 * @sa c4_Property
 */
c4_View c4_View::operator, (const c4_Property& prop_) const
{
  c4_View view = Clone();
  view.AddProperty(prop_);
  return view;
}
Exemplo n.º 21
0
UIStaticText *UIStaticText::CloneStaticText()
{
	return (UIStaticText *)Clone();
}
Exemplo n.º 22
0
/** Create view with all duplicate rows omitted
 *
 * This view operation is based on a read-only custom viewer.
 */
c4_View c4_View::Unique() const
{
  c4_IntProp count ("#N#");
  return Counts(Clone(), count).ProjectWithout(count);
}
Exemplo n.º 23
0
PolyMesh* PolyMesh::ToPolyMesh()
{
	return (PolyMesh*)Clone();
}
void clone( const TrafficIPC::Disturbances& cloneThese,
            TrafficIPC::Disturbances& toMe ) {
   std::transform( cloneThese.begin(), cloneThese.end(),
                   std::back_inserter( toMe ), Clone() );
}
Exemplo n.º 25
0
void XXObjectRectangle::cloneRect(XSWFCONTEXT&cnt,XXVARLIST&list)
{
	cnt.pStack->Push((Clone()));
}
Exemplo n.º 26
0
	tuple(const tuple &rhs)
	{
		Clone(rhs);
		return;
	}
Exemplo n.º 27
0
MyMat::MyMat(const MyMat &src):m_data(NULL)
{
	Clone(src);
}
Exemplo n.º 28
0
	tuple & operator=(const tuple &rhs)
	{
		return Clone(rhs);
	}
Exemplo n.º 29
0
	CImageAttribute::CImageAttribute(const CImageAttribute& image)
	{
		Clone(image);
	}
Exemplo n.º 30
0
// Process the received packet
BLOCK *UdpAccelProcessRecvPacket(UDP_ACCEL *a, UCHAR *buf, UINT size, IP *src_ip, UINT src_port)
{
	UCHAR key[UDP_ACCELERATION_PACKET_KEY_SIZE];
	UCHAR *iv;
	CRYPT *c;
	UINT64 my_tick, your_tick;
	UINT inner_size;
	UCHAR *inner_data = NULL;
	UINT pad_size;
	UCHAR *verify;
	bool compress_flag;
	BLOCK *b = NULL;
	UINT cookie;
	// Validate arguments
	if (a == NULL || buf == NULL || size == 0 || src_ip == NULL)
	{
		return NULL;
	}

	if (a->PlainTextMode == false)
	{
		// IV
		if (size < UDP_ACCELERATION_PACKET_IV_SIZE)
		{
			return NULL;
		}
		iv = buf;
		buf += UDP_ACCELERATION_PACKET_IV_SIZE;
		size -= UDP_ACCELERATION_PACKET_IV_SIZE;

		// Calculate the key
		UdpAccelCalcKey(key, a->YourKey, iv);

		if (false)
		{
			char tmp1[256];
			char tmp2[256];
			char tmp3[256];
			BinToStr(tmp1, sizeof(tmp1), a->YourKey, sizeof(a->YourKey));
			BinToStr(tmp2, sizeof(tmp2), iv, UDP_ACCELERATION_PACKET_IV_SIZE);
			BinToStr(tmp3, sizeof(tmp3), key, sizeof(key));
			Debug("Your Key: %s\n"
				  "IV      : %s\n"
				  "Comm Key: %s\n",
				tmp1, tmp2, tmp3);
		}

		// Decryption
		c = NewCrypt(key, UDP_ACCELERATION_PACKET_KEY_SIZE);
		Encrypt(c, buf, buf, size);
		FreeCrypt(c);
	}

	// Cookie
	if (size < sizeof(UINT))
	{
		return NULL;
	}
	cookie = READ_UINT(buf);
	buf += sizeof(UINT);
	size -= sizeof(UINT);

	if (cookie != a->MyCookie)
	{
		return NULL;
	}

	// My Tick
	if (size < sizeof(UINT64))
	{
		return NULL;
	}
	my_tick = READ_UINT64(buf);
	buf += sizeof(UINT64);
	size -= sizeof(UINT64);

	// Your Tick
	if (size < sizeof(UINT64))
	{
		return NULL;
	}
	your_tick = READ_UINT64(buf);
	buf += sizeof(UINT64);
	size -= sizeof(UINT64);

	// inner_size
	if (size < sizeof(USHORT))
	{
		return NULL;
	}
	inner_size = READ_USHORT(buf);
	buf += sizeof(USHORT);
	size -= sizeof(USHORT);

	// compress_flag
	if (size < sizeof(UCHAR))
	{
		return NULL;
	}
	compress_flag = *((UCHAR *)buf);
	buf += sizeof(UCHAR);
	size -= sizeof(UCHAR);

	if (size < inner_size)
	{
		return NULL;
	}

	// inner_data
	if (inner_size >= 1)
	{
		inner_data = buf;
		buf += inner_size;
		size -= inner_size;
	}

	if (a->PlainTextMode == false)
	{
		// padding
		if (size < UDP_ACCELERATION_PACKET_IV_SIZE)
		{
			return false;
		}
		pad_size = size - UDP_ACCELERATION_PACKET_IV_SIZE;
		buf += pad_size;
		size -= pad_size;

		// verify
		if (size != UDP_ACCELERATION_PACKET_IV_SIZE)
		{
			return NULL;
		}

		verify = buf;

		if (IsZero(verify, UDP_ACCELERATION_PACKET_IV_SIZE) == false)
		{
			return NULL;
		}
	}

	if (my_tick < a->LastRecvYourTick)
	{
		if ((a->LastRecvYourTick - my_tick) >= ((UINT64)UDP_ACCELERATION_WINDOW_SIZE_MSEC))
		{
			return NULL;
		}
	}

	a->LastRecvMyTick = MAX(a->LastRecvMyTick, your_tick);
	a->LastRecvYourTick = MAX(a->LastRecvYourTick, my_tick);

	if (inner_size >= 1)
	{
		b = NewBlock(Clone(inner_data, inner_size), inner_size, compress_flag ? -1 : 0);
	}

	if (a->LastSetSrcIpAndPortTick < a->LastRecvYourTick)
	{
		a->LastSetSrcIpAndPortTick = a->LastRecvYourTick;

		Copy(&a->YourIp, src_ip, sizeof(IP));
		a->YourPort = src_port;
	}

	if (a->LastRecvMyTick != 0)
	{
		if ((a->LastRecvMyTick + (UINT64)(UDP_ACCELERATION_WINDOW_SIZE_MSEC)) >= a->Now)
		{
			a->LastRecvTick = a->Now;

			a->IsReachedOnce = true;

			if (a->FirstStableReceiveTick == 0)
			{
				a->FirstStableReceiveTick = a->Now;
			}
		}
	}

	return b;
}