Definición de mi propio componente de circuito digital de caja blanca personalizado

Definición de mi propio componente de circuito digital de caja blanca personalizado

Tikz tiene un montón de componentes de circuitos digitales útiles, básicos o complejos. aquí necesitoalgunopropio, ni siquiera necesariamente uno de los más convenientes. Pero tomemos un ejemplo bastante conveniente: un comparador de magnitud.

me gustaria tener estocomparador de magnitudcomponente para mi tarea, con sus puertos de señal definidos como anchors. Puedo hacer una caja con etiquetas en los puertos y un nombre, pero eso es¡no es suficiente!

También necesito mostrar lo que hay dentro. Los detalles no irán más allá de las puertas, no quiero los transistores cerca, pero sí necesito las puertas.

Esto es lo que tengo entre manos hasta ahora, la mayor parte simplemente copiado/imitado deeste (¿famoso?) ejemplo de flip-flop de datos:

\makeatletter

% Magnitude Comparator (magn comparator) shape
\pgfdeclareshape{magn comparator}
{
    % The 'minimum width' and 'minimum height' keys, not the content, determine
    % the size
    \savedanchor\northeast
    {%
        \pgfmathsetlength\pgf@x{\pgfshapeminwidth}%
        \pgfmathsetlength\pgf@y{\pgfshapeminheight}%
        \pgf@x=0.5\pgf@x
        \pgf@y=0.5\pgf@y
    }
    % This is redundant, but makes some things easier:
    \savedanchor\southwest
    {%
        \pgfmathsetlength\pgf@x{\pgfshapeminwidth}%
        \pgfmathsetlength\pgf@y{\pgfshapeminheight}%
        \pgf@x=-0.5\pgf@x
        \pgf@y=-0.5\pgf@y
    }
    % Inherit from rectangle
    \inheritanchorborder[from=rectangle]

    % Define same anchor a normal rectangle has
    \anchor{center}{\pgfpointorigin}
    \anchor{north}{\northeast \pgf@x=0pt}
    \anchor{east}{\northeast \pgf@y=0pt}
    \anchor{south}{\southwest \pgf@x=0pt}
    \anchor{west}{\southwest \pgf@y=0pt}
    \anchor{north east}{\northeast}
    \anchor{north west}{\northeast \pgf@x=-\pgf@x}
    \anchor{south west}{\southwest}
    \anchor{south east}{\southwest \pgf@x=-\pgf@x}
    \anchor{text}
    {
        \pgfpointorigin
        \advance\pgf@x by -.5\wd\pgfnodeparttextbox%
        \advance\pgf@y by -.5\ht\pgfnodeparttextbox%
        \advance\pgf@y by +.5\dp\pgfnodeparttextbox%
    }

    % Define anchors for input signal ports
    \anchor{input gt}
    {
        \pgf@process{\southwest}%
        \pgf@y=-.5\pgf@y%
    }
    \anchor{input eq}
    {
        \pgf@process{\southwest}%
        \pgf@y=0pt%
    }
    \anchor{input lt}
    {
        \pgf@process{\southwest}%
        \pgf@y=.5\pgf@y%
    }
    \anchor{input a}
    {
        \pgf@process{\northeast}%
        \pgf@x=-.3\pgf@x%
    }
    \anchor{input b}
    {
        \pgf@process{\northeast}%
        \pgf@x=.3\pgf@x%
    }

    % Define anchors for output signal ports
    \anchor{output gt}
    {
        \pgf@process{\northeast}%
        \pgf@y=.5\pgf@y%
    }
    \anchor{output eq}
    {
        \pgf@process{\northeast}%
        \pgf@y=0pt%
    }
    \anchor{output lt}
    {
        \pgf@process{\northeast}%
        \pgf@y=-.5\pgf@y%
    }

    % Draw the rectangle box and the port labels
    \backgroundpath
    {
        % Rectangle box
        \pgfpathrectanglecorners{\southwest}{\northeast}
        % \node [and gate] (kek) at (0, 0) {};
    }
}

% Define default style for this node
\tikzset
{
    every magn comparator node/.style =
    {
        draw,
        minimum width = 2cm,
        minimum height = 2cm,
        thick,
        inner sep = 1mm,
        outer sep = 0pt,
        cap = round
    }
}

\makeatother

Esto está en un archivo separado que incluyo en el preámbulo de mi archivo principal de LaTeX.

Aquí no hay puertas, solo dibuja la caja. Intenté simplemente colocar una puerta AND aleatoria de la forma habitual que hago fuera de esta \pgfdeclareshapecosa, lo que por supuesto no funcionó. Comenté eso, ese intento.

Debería haber una manera de definir más formas además de las formas existentes. ¿Qué es?

Editar:Espero tener algo como esto en mis manos, que debería poder colocar y puertos a los que pueda llegar fácilmente como anclas, similar a como ocurre con una puerta AND/OR/NOR/XOR/NAND:

ingrese la descripción de la imagen aquí

Tenga en cuenta que el interior de la caja en realidad no funciona como un comparador de magnitud, es sólo un ejemplo ficticio de lo que espero.

Respuesta1

Dependiendo de la complejidad de sus casos de uso y de cuántas de estas formas necesite... aquí es un comienzo.

La respuesta consiste en lo siguiente:

  • Una declaración de forma que toma prestada la rectangle eedefinición de (que es solo una forma circuits.eeprestada con anclajes ).rectangle.input.output

    También tomo prestado del enlace.Ejemplo de textopara el texto dentro de la definición de una forma. Los anclajes se establecen con \pgfpointlineattime(esto es similar a la posclave a lo largo de una línea recta o al factor dentro calcde la ($(<p1>)!<factor>!(<p2>)$)notación).

    Si tiene muchas más de estas formas que necesitan varios de estos anclajes diferentes a lo largo del borde de un rectángulo, esto se puede serializar con claves fey y un bucle dentro de la declaración de la forma. Esto también se aplica a los textos.

  • Ahora que tenemos una forma con anclajes y textos podemos usarla. Para una forma de circuito adecuada declaramos un símbolo con circuit declare symboly lo configuramos con set <symbol name> graphic.

    Las teclas circuit symbol sizese establecen minimum widthy minimum heighten relación con circuit symbol unit(una dimensión TeX debajo del capó). Esto lo hace escalable en relación con otros símbolos de circuito. La transform shapeclave es necesaria para hacerlo girar a lo largo de circuits' tocaminos.

  • A path pictureque utiliza el código propuesto deotra respuesta mia. Para configurar un sistema de coordenadas local que gire y escale con su nodo: La coordenada (0, 0)está en el centro del nodo. ElXEl vector apunta al east(= output), elyvector al ancla norte. Esto es importante para las especificaciones de coordenadas, (left:.2)ya que utiliza .2la mitad de la dimensión horizontal del nodo.yla rotación aplicada.

    Los símbolos del circuito dentro path pictureobtienen las opciones gray(al igual que las líneas) y circuit symbol unit=.1cmreducen los símbolos a un tamaño apropiado. Puede que sea necesario jugar con este valor para conseguir el tamaño correcto. También es posible hacer que esto dependa del sistema de coordenadas local antes mencionado con las dimensiones \pgf@xxy \pgf@yy.

    Obviamente, si necesita varios símbolos con el mismo anclaje y diseño de conexión pero con diferentes puertas , es posible hacer que la definición de formas sea maleable de acuerdo con tres claves de valores que se establecerían en este caso en y not gate.nand gatenor gate

he usado mipaths.orthobibliotecapara las conexiones dentro del path picture. Obviamente puedes usar cualquier forma de conectar estas líneas.

Código

\documentclass[tikz]{standalone}
\usetikzlibrary{circuits.ee,circuits.logic.US,paths.ortho}
\makeatletter
\pgfdeclareshape{my complicated box}{%
  \inheritsavedanchors[from=rectangle ee]
  \inheritanchor[from=rectangle ee]{center}
  \inheritanchor[from=rectangle ee]{north}
  \inheritanchor[from=rectangle ee]{south}
  \inheritanchor[from=rectangle ee]{east}
  \inheritanchor[from=rectangle ee]{west}
  \inheritanchor[from=rectangle ee]{north east}
  \inheritanchor[from=rectangle ee]{north west}
  \inheritanchor[from=rectangle ee]{south east}
  \inheritanchor[from=rectangle ee]{south west}
  \inheritanchor[from=rectangle ee]{input}
  \inheritanchor[from=rectangle ee]{output}
  \inheritanchorborder[from=rectangle ee]
  \inheritbackgroundpath[from=rectangle ee]
  \anchor{eq in} {\pgf@sh@reanchor{\pgf@sm@shape@name}{input}}
  \anchor{eq out}{\pgf@sh@reanchor{\pgf@sm@shape@name}{output}}
  \anchor{lt in}{%
    \pgfpointlineattime{.2}{\southwest}
    {\southwest\pgf@xc\pgf@x\northeast\pgf@x\pgf@xc}}
  \anchor{gt in}{%
    \pgfpointlineattime{.8}{\southwest}
    {\southwest\pgf@xc\pgf@x\northeast\pgf@x\pgf@xc}}
  \anchor{gt out}{%
    \pgfpointlineattime{.3}{\northeast}
    {\southwest\pgf@yc\pgf@y\northeast\pgf@y\pgf@yc}}
  \anchor{lt out}{%
    \pgfpointlineattime{.7}{\northeast}
    {\southwest\pgf@yc\pgf@y\northeast\pgf@y\pgf@yc}}
  \anchor{a}{%
    \pgfpointlineattime{.4}
      {\southwest\pgf@xc\pgf@x\northeast\pgf@x\pgf@xc}{\northeast}}
  \anchor{b}{%
    \pgfpointlineattime{.6}
      {\southwest\pgf@xc\pgf@x\northeast\pgf@x\pgf@xc}{\northeast}}
  \beforebackgroundpath{%
    \begingroup
      \tikzset{my complicated box/labels/.try}\tikz@textfont
      \pgf@sh@reanchor{\pgf@sm@shape@name}{eq in}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},left,%
                x=\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{eq}_{\mathrm{in}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{eq out}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},right,%
                x=-\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{eq}_{\mathrm{out}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{gt in}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},left,%
                x=\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{gt}_{\mathrm{in}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{gt out}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},right,%
                x=-\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{gt}_{\mathrm{out}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{lt in}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},left,%
                x=\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{lt}_{\mathrm{in}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{lt out}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},right,%
                x=-\pgfkeysvalueof{/pgf/inner xsep}]{$\mathrm{lt}_{\mathrm{out}}$}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{a}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},top,%
                y=-\pgfkeysvalueof{/pgf/inner ysep}]{a\vphantom{b}}
      \pgf@sh@reanchor{\pgf@sm@shape@name}{b}
      \pgftext[at=\pgfqpoint{\pgf@x}{\pgf@y},top,%
                y=-\pgfkeysvalueof{/pgf/inner ysep}]{b}
    \endgroup}
}
\makeatother
\tikzset{my complicated box/labels/.style={font=\footnotesize, inner sep=.1667em}}
\tikzset{
  circuit declare symbol=my complicated symbol,
  set my complicated symbol graphic={
    draw, shape=my complicated box, circuit symbol size=width 10 height 8,
    transform shape,
    path picture={
      \expandafter\let\expandafter\tfn\csname tikz@fig@name\endcsname
      \pgftransformshift{\pgfpointanchor{\tfn}{center}}%
      \pgfsetxvec{\pgfpointdiff{\pgfpointanchor{\tfn}{center}}
                 {\pgfpointanchor{\tfn}{east}}}%
      \pgfsetyvec{\pgfpointdiff{\pgfpointanchor{\tfn}{center}}
                 {\pgfpointanchor{\tfn}{north}}}
      \tikzset{every circuit symbol/.append style={circuit symbol unit=.1cm, gray}}
      \path[thin, draw=gray]
        (\tfn.eq in) to[not gate=near end] (\tfn.eq out)
        (\tfn.lt out) to ++ (left:.2)
          node[anchor=output, logic gate inputs=nn, nand gate] (\tfn-nand) {}
        (\tfn-nand.input 2) to[-|-=.6] (\tfn.lt in)
        (\tfn-nand.input 1) to[-|] (\tfn.a)
        (\tfn.gt out) to ++ (left:.2)
          node[anchor=output, logic gate inputs=nn, nor gate] (\tfn-nor) {}
        (\tfn-nor.input 2) to[-|-=.6] (\tfn.gt in)
        (\tfn-nor.input 1) to[-|] (\tfn.b);
    }},
}
\begin{document}
\begin{tikzpicture}[circuit logic US]
\draw (0,0) to[my complicated symbol] ++ (30:4);
\end{tikzpicture}
\end{document}

Producción

ingrese la descripción de la imagen aquí

Respuesta2

Una posible solución con pics. Es difícil de usar pic-anchorspara posicionamiento (Anclaje de fotografías TiKZ) pero sirven como puntos de referencia para establecer vínculos entre ellos.

\documentclass[tikz,border=2mm]{standalone}

\usetikzlibrary{positioning,circuits.logic.US, fit}

\tikzset{
    mycircuit/.pic={
        \begin{scope}[circuit logic US]
        \node[gray, thick, draw, nor gate] (-gt) at (2,0.75) {};
        \node[gray, thick, draw, not gate] (-eq) at (2,0) {};
        \node[gray, thick, draw, nand gate] (-lt) at (2,-0.75) {};

        \draw[gray] (-gt.output)--++(3mm,0) 
             coordinate[label={[black]left:$\mathrm{gt}_\mathrm{out}$}] (-gtout);

        \draw[gray] (-eq.output)--(-eq.output-|-gtout) 
             coordinate[label={[black]left:$\mathrm{eq}_\mathrm{out}$}] (-eqout);

        \draw[gray] (-lt.output)--(-lt.output-|-gtout) 
             coordinate[label={[black]left:$\mathrm{lt}_\mathrm{out}$}] (-eqout);

        \draw[gray] (-gt.input 1)-|++(-3mm,.5cm) 
             coordinate[label={[black]below:$\mathrm{b}$}] (-b);

        \draw[gray] (-lt.input 1)-|([xshift=-6mm]-b.center) 
             coordinate[label={[black]below:$\mathrm{a}$}] (-a);

        \draw[gray] (-eq.input)--++(-2cm,0) 
             coordinate[label={[black]right:$\mathrm{eq}_\mathrm{in}$}] (-eqin);

        \draw[gray] (-gt.input 2)--++(-1.2cm,0) |- ([yshift=1cm]-eqin.center)  
             coordinate[label={[black]right:$\mathrm{gt}_\mathrm{in}$}] (-gtin);

        \draw[gray] (-lt.input 2)--++(-1.2cm,0) |- ([yshift=-1cm]-eqin.center)  
             coordinate[label={[black]right:$\mathrm{lt}_\mathrm{in}$}] (-ltin);

        \node[draw, fit={(-ltin) (-b) ([yshift=-.5cm]-lt.input 2) (-gtout)}, 
              inner sep=0pt] (-box) {};
        \end{scope}
    }}

\begin{document}
\begin{tikzpicture}

\pic (a) at (0,0) {mycircuit};

\pic (b) at (5,1) {mycircuit};

\draw (a-gtout) -- (b-gtin);
\draw ([yshift=2cm]a-a) coordinate (aux)--(a-a);
\draw ([yshift=-5mm]aux)-|(b-a);
\end{tikzpicture}
\end{document}

ingrese la descripción de la imagen aquí

información relacionada