Exemplo n.º 1
0
AnalogInputs::ValueType Resistance::getReadableRth_calibrateI(AnalogInputs::Name name)
{
    Resistance R;
    R.uI_ = AnalogInputs::calibrateValue(name, uI_);
    R.iV_ = iV_;
    return R.getReadableRth();
}
AnalogInputs::ValueType TheveninMethod::getReadableWiresRth()
{
    Resistance R;
    R.iV_ =  AnalogInputs::getRealValue(AnalogInputs::Vout);
    R.iV_ -= AnalogInputs::getRealValue(AnalogInputs::Vbalancer);
    R.uI_ = AnalogInputs::getRealValue(AnalogInputs::Iout);
    return R.getReadableRth();

}
Resistance *Structure::get_resistance_from_resistance_name(char *resistance_name)
{
  Resistance *resist;

  if (strcmp(resistance_name,"") == 0)
    return NULL;

  resist = list_resistances.initialize();
  for(; resist != NULL; resist = list_resistances.iterate() )
    if (strcmp(resistance_name,resist->name()) == 0)
      return resist;

  return NULL;
}
Resistance *Structure::get_resistance_from_node_names(char *node1_name, char *node2_name)
{
  Resistance *resist;

  if ((strcmp(node1_name,"") == 0)||(strcmp(node2_name,"") == 0))
    return NULL;

  resist = list_resistances.initialize();
  for(; resist != NULL; resist = list_resistances.iterate() )
    if ((strcmp(node1_name,resist->node_name(1)) == 0) &&
        (strcmp(node2_name,resist->node_name(2)) == 0))
      return resist;

  return NULL;
}
void Structure::find_load_resistance()
{
  Ext_Node_Pair *ext_node_pair;
  Resistance *resist;
  char * nodeName1, *nodeName2;

  for (resist = list_resistances.initialize(); resist!=NULL;
       resist=list_resistances.iterate())
  {
    if ((resist->get_node(1) !=NULL) && (resist->get_node(2) !=NULL))
    {
      nodeName1=resist->node_name(1);
      nodeName2=resist->node_name(2);
      ext_node_pair=get_ext_node_pair_from_node_names(nodeName1, nodeName2);
      ext_node_pair->connect_to_resistance(resist);
    }
  }

}
void Structure::connect_resistances_meshes()
{
  Resistance *resist;
  List<Internal_Node> *list_int_nodes;
  Internal_Node *int_node_ptr;
  panel<double> *panel1_ptr, *panel2_ptr;
  long int mesh_number_Mps, mesh_number_Mrs;

  // precaution
/*  if (mesh_mats.Mp_ptr == NULL)
  {
    printf ("Errare humanum est: Structure::connect_resistances_meshes()\n");
    exit (-1);
  }
*/
  // get number of already existing meshes (in Mp); number of meshes in Mrs is 0;
 // mesh_number_Mps = (mesh_mats.Mps_ptr->get_n_lines()) + 1;
  mesh_number_Mps = (mesh_mats.Mps_ptr.numRow()) + 1;
  mesh_number_Mrs = 0+1;

  for (resist=list_resistances.initialize(); resist != NULL;
       resist=list_resistances.iterate() )
  {

    // get panel connected to 1st node of this resistance
    if ((int_node_ptr = ((((resist->get_node(1))->real_node())->
                          get_list_internal_nodes())->initialize())) == NULL)
    {
      printf ("Error: Structure::connect_resistances_meshes() - nothing "
              "is connects to node %s of Resistance %s.\n",
              resist->node_name(1), resist->name() );
      exit(-1);
    }
    if ((panel1_ptr = int_node_ptr->get_first_panel_ptr()) == NULL)
    {
      printf ("Error: Structure::connect_resistances_meshes() - no panels "
              "on this internal node ?\n");
      exit(-1);
    }

    // get panel connected to 2nd node of this resistance
    if ((int_node_ptr = ((((resist->get_node(2))->real_node())->
                          get_list_internal_nodes())->initialize())) == NULL)
    {
      printf ("Error: Structure::connect_resistances_meshes() - nothing "
              "is connects to node %s of Resistance %s.\n",
              resist->node_name(2), resist->name() );
      exit(-1);
    }
    if ((panel2_ptr = int_node_ptr->get_first_panel_ptr()) == NULL)
    {
      printf ("Error: Structure::connect_resistances_meshes() - no panels "
              "on this internal node ?\n");
      exit(-1);
    }

    // add mesh in Mps and Mrs
    //mesh_mats.Mps_ptr->add_entry (0,mesh_number_Mps++, panel1_ptr, -1, panel2_ptr, 1, NULL);
    //mesh_mats.Mrs_ptr->add_entry (0, mesh_number_Mrs++, resist, 1, NULL);
	mesh_mats.Mps_ptr.resize_insertElement(mesh_number_Mps, panel1_ptr->get_number(), -1);
	mesh_mats.Mps_ptr.insertElement(mesh_number_Mps-1, panel2_ptr->get_number(), 1);
		mesh_number_Mps++;
	mesh_mats.Mrs_ptr.resize_insertElement(mesh_number_Mrs++, resist->get_number(),1);
  
  }
}
size_t DfpnSolver::MID(const DfpnBounds& maxBounds, DfpnHistory& history)
{
    maxBounds.CheckConsistency();
    HexAssert(maxBounds.phi > 1);
    HexAssert(maxBounds.delta > 1);

    int depth = history.Depth();
    size_t prevWork = 0;
    bitset_t maxProofSet;
    float evaluationScore;
    HexColor colorToMove = m_state->ToPlay();
    DfpnChildren children;
    {
        DfpnData data;
        if (TTRead(*m_state, data)) 
        {
            children = data.m_children;
            maxProofSet = data.m_maxProofSet;
            prevWork = data.m_work;
            evaluationScore = data.m_evaluationScore;
            if (!maxBounds.GreaterThan(data.m_bounds))
                // Estimated bounds are larger than we had
                // anticipated. The calling state must have computed
                // the max bounds with out of date information, so just
                // return here without doing anything: the caller will
                // now update to this new info and carry on.
                return 0;
        }
        else
        {
            m_workBoard->GetPosition().SetPosition(m_state->Position());
            m_workBoard->ComputeAll(colorToMove);
            ++m_numVCbuilds;

            // Compute the maximum possible proof set if colorToMove wins.
            // This data is used to prune siblings of this state.
            maxProofSet = ProofUtil::MaximumProofSet(*m_workBoard, colorToMove);

            if (EndgameUtils::IsDeterminedState(*m_workBoard, colorToMove))
            {
                ++m_numTerminal;
                DfpnBounds terminal;
                if (EndgameUtils::IsWonGame(*m_workBoard, colorToMove))
                    DfpnBounds::SetToWinning(terminal);
                else 
                    DfpnBounds::SetToLosing(terminal);
                
                if (m_useGuiFx && depth == 1)
                {
                    m_guiFx.UpdateCurrentBounds(terminal);
                    m_guiFx.Write();
                }
                TTWrite(*m_state, DfpnData(terminal, DfpnChildren(), 
                                  INVALID_POINT, 1, maxProofSet, 0.0));
                return 1;
            }
            bitset_t childrenBitset 
                = EndgameUtils::MovesToConsider(*m_workBoard, colorToMove);

            m_considerSetSize.Add(childrenBitset.count());
            Resistance resist;
            resist.Evaluate(*m_workBoard);
            evaluationScore = (colorToMove == BLACK) 
                ? resist.Score() : -resist.Score();
            m_allEvaluation.Add(evaluationScore);
            std::vector<std::pair<HexEval, HexPoint> > mvsc;
            for (BitsetIterator it(childrenBitset); it; ++it) 
            {
                HexEval score = resist.Score(*it);
                mvsc.push_back(std::make_pair(-score, *it));
            }
            stable_sort(mvsc.begin(), mvsc.end());
            std::vector<HexPoint> sortedChildren;
            for (size_t i = 0; i < mvsc.size(); ++i)
                sortedChildren.push_back(mvsc[i].second);
            children.SetChildren(sortedChildren);
        }
    }

    ++m_numMIDcalls;
    size_t localWork = 1;

    // Not thread safe: perhaps move into while loop below later...
    std::vector<DfpnData> childrenData(children.Size());
    for (size_t i = 0; i < children.Size(); ++i)
        LookupData(childrenData[i], children, i, *m_state);
    // Index used for progressive widening
    size_t maxChildIndex = ComputeMaxChildIndex(childrenData);

    if (m_useGuiFx && depth == 0)
        m_guiFx.SetChildren(children, childrenData);

    hash_t currentHash = m_state->Hash();
    HexPoint bestMove = INVALID_POINT;
    DfpnBounds currentBounds;
    do
    {
        UpdateBounds(currentBounds, childrenData, maxChildIndex);

        if (m_useGuiFx && depth == 1)
        {
            m_guiFx.UpdateCurrentBounds(currentBounds);
            m_guiFx.Write();
        }

        if (!maxBounds.GreaterThan(currentBounds))
            break;

        // Select most proving child
        int bestIndex = -1;
        DfpnBoundType delta2 = DfpnBounds::INFTY;
        SelectChild(bestIndex, delta2, childrenData, maxChildIndex);
        bestMove = children.FirstMove(bestIndex);

        // Compute maximum bound for child
        const DfpnBounds childBounds(childrenData[bestIndex].m_bounds);
        DfpnBounds childMaxBounds;
        childMaxBounds.phi = maxBounds.delta 
            - (currentBounds.delta - childBounds.phi);
        childMaxBounds.delta = std::min(maxBounds.phi, delta2 + 1);
        HexAssert(childMaxBounds.GreaterThan(childBounds));
        if (delta2 != DfpnBounds::INFTY)
            m_deltaIncrease.Add(childMaxBounds.delta - childBounds.delta);

        // Recurse on best child
        if (m_useGuiFx && depth == 0)
            m_guiFx.PlayMove(colorToMove, bestIndex);
        children.PlayMove(bestIndex, *m_state);
        history.Push(bestMove, currentHash);
        localWork += MID(childMaxBounds, history);
        history.Pop();
        children.UndoMove(bestIndex, *m_state);

        if (m_useGuiFx && depth == 0)
            m_guiFx.UndoMove();

        // Update bounds for best child
        LookupData(childrenData[bestIndex], children, bestIndex, *m_state);

        // Compute some stats when find winning move
        if (childrenData[bestIndex].m_bounds.IsLosing())
        {
            m_moveOrderingIndex.Add(bestIndex);
            m_moveOrderingPercent.Add(bestIndex / (double)childrenData.size());
            m_totalWastedWork += prevWork + localWork
                - childrenData[bestIndex].m_work;
        }
        else if (childrenData[bestIndex].m_bounds.IsWinning())
            maxChildIndex = ComputeMaxChildIndex(childrenData);

        // Shrink children list using knowledge of bestMove child's proof set.
        // That is, if this child is losing, conclude what other children
        // must also be losing (i.e. cannot interfere with the proof set
        // that disproves this child).
        // And of course if this child is winning, no need to explore
        // these other siblings either.
        {
            /* @todo Perhaps track allChildren instead of recomputing? */
            bitset_t allChildren;
            for (std::vector<HexPoint>::iterator it
                     = children.m_children.begin();
                 it != children.m_children.end(); ++it)
            {
                allChildren.set(*it);
            }
            bitset_t canPrune = allChildren
                - childrenData[bestIndex].m_maxProofSet;
            canPrune.reset(bestMove);
            int pruneCount = canPrune.count();

            if (pruneCount)
            {
                m_prunedSiblingStats.Add(pruneCount);
                /*
                LogInfo() << "Pruning " << pruneCount
                          << " moves via " << bestMove
                          << ".\nChildren:\n" << m_brd->Write(allChildren)
                          << "\nRemoving...\n" << m_brd->Write(canPrune)
                          << "\n";
                */
                DeleteChildren(children, childrenData, canPrune);
                maxChildIndex = ComputeMaxChildIndex(childrenData);
                if (m_useGuiFx && depth == 0)
                    m_guiFx.SetChildren(children, childrenData);
            }
        }
    } while (!CheckAbort());

    if (m_useGuiFx && depth == 0)
        m_guiFx.WriteForced();

    // Find the most delaying move for losing states, and the smallest
    // winning move for winning states.
    if (currentBounds.IsSolved())
    {
        m_allSolvedEvaluation.Add(evaluationScore);
        if (currentBounds.IsLosing())
        {
            m_losingEvaluation.Add(evaluationScore);
            std::size_t maxWork = 0;
            for (std::size_t i = 0; i < children.Size(); ++i)
            {
                if (childrenData[i].m_work > maxWork)
                {
                    maxWork = childrenData[i].m_work;
                    bestMove = children.FirstMove(i);
                }
            }
        }
        else
        {
            m_winningEvaluation.Add(evaluationScore);
            std::size_t minWork = DfpnBounds::INFTY;
            for (std::size_t i = 0; i < children.Size(); ++i)
            {
                if (childrenData[i].m_bounds.IsLosing() 
                    && childrenData[i].m_work < minWork)
                {
                    minWork = childrenData[i].m_work;
                    bestMove = children.FirstMove(i);
                }
            }
        }
    }
    
    // Store search results and notify listeners
    DfpnData data(currentBounds, children, bestMove, localWork + prevWork, 
                  maxProofSet, evaluationScore);
    TTWrite(*m_state, data);
    if (data.m_bounds.IsSolved())
        NotifyListeners(history, data);
    return localWork;
}
/** Does a 1-ply search.

    For each move in the consider set, if the move is a win, returns
    true and the move. If the move is a loss, prune it out of the
    consider set if there are non-losing moves in the consider set.
    If all moves are losing, perform no pruning, search will resist.

    Returns true if there is a win, false otherwise. 

    @todo Is it true that MoHex will resist in the strongest way
    possible?
*/
bool MoHexPlayer::PerformPreSearch(HexBoard& brd, HexColor color, 
                                   bitset_t& consider, double maxTime, 
                                   PointSequence& winningSequence)
{
   
    bitset_t losing;
    HexColor other = !color;
    PointSequence seq;
    bool foundWin = false;

    SgTimer elapsed;
    Resistance resist;
    resist.Evaluate(brd);
    std::vector<HexPoint> moves;
    SortConsiderSet(consider, resist, moves);
    for (std::size_t i = 0; i < moves.size() && !foundWin; ++i) 
    {
        if (elapsed.GetTime() > maxTime)
        {
            LogInfo() << "PreSearch: max time reached "
                      << '(' << i << '/' << moves.size() << ").\n";
            break;
        }
        brd.PlayMove(color, moves[i]);
        seq.push_back(moves[i]);
        if (EndgameUtil::IsLostGame(brd, other)) // Check for winning move
        {
            winningSequence = seq;
            foundWin = true;
        }	
        else if (EndgameUtil::IsWonGame(brd, other))
            losing.set(moves[i]);
        seq.pop_back();
        brd.UndoMove();
    }

    // Abort if we found a one-move win
    if (foundWin)
        return true;

    // Backing up cannot cause this to happen, right? 
    BenzeneAssert(!EndgameUtil::IsDeterminedState(brd, color));

    // Use the backed-up ice info to shrink the moves to consider
    if (m_backup_ice_info) 
    {
        bitset_t new_consider 
            = EndgameUtil::MovesToConsider(brd, color) & consider;

        if (new_consider.count() < consider.count()) 
        {
            consider = new_consider;       
            LogFine() << "$$$$$$ new moves to consider $$$$$$" 
                      << brd.Write(consider) << '\n';
        }
    }

    // Subtract any losing moves from the set we consider, unless all of them
    // are losing (in which case UCT search will find which one resists the
    // loss well).
    if (losing.any()) 
    {
	if (BitsetUtil::IsSubsetOf(consider, losing)) 
	    LogInfo() << "************************************\n"
                      << " All UCT root children are losing!!\n"
                      << "************************************\n";
        else 
        {
            LogFine() << "Removed losing moves: " << brd.Write(losing) << '\n';
	    consider = consider - losing;
	}
    }

    BenzeneAssert(consider.any());
    LogInfo() << "Moves to consider:\n" << brd.Write(consider) << '\n';
    return false;
}
Exemplo n.º 9
0
void PhysicsTypesTest::resistanceSimpleTest()
{
  using Mdt::Numeric::Resistance;
  using Mdt::Numeric::Double;

  /*
   * Constructions
   */
  // Default constructed
  Resistance r;
  QVERIFY(r.isNull());
  // Contruct with a value
  Resistance r2 = Resistance(1.5);
  QVERIFY(!r2.isNull());
  QCOMPARE(r2.value().toDouble(), 1.5);
  /*
   * Set
   */
  // Set from double
  QVERIFY(r.isNull());
  r = Resistance(2.0);
  QVERIFY(!r.isNull());
  QCOMPARE(r.value().toDouble(), 2.0);
  // Affectation of other Resistance
  r2 = Resistance(1.5);
  r = r2;
  QCOMPARE(r.value().toDouble(), 1.5);
  /*
   * Clear
   */
  QVERIFY(!r.isNull());
  r.clear();
  QVERIFY(r.isNull());
  /*
   * Get from QVariant
   */
  r = Resistance::fromQVariant(10.0);
  QVERIFY(!r.isNull());
  QCOMPARE(r.value().toDouble(), 10.0);
  r = Resistance::fromQVariant(QVariant());
  QVERIFY(r.isNull());
  /*
   * QDebug stream operator
   */
  qDebug() << "r: " << r;
  r = Resistance(2.5e3);
  qDebug() << "r: " << r;
}